functiongradlesubproject

Gradle add function to subproject (best practice)


This is a question that has multiple parts.

Gradle seems to have 2 ways to define a function

Type one:

def func1 = { param -> ...}

Type 2

def func2 (OptionalType param){...}

I prefer to use Type 2 not only because I don't know how to define the type for a parameter for func1 (question part 1 is how to set the type for a func type 1 param), but also because it reads better.

But I found that I can do

subprojects { ext.func1 = func1 }

But

subprojects { ext.func2 = func2 }

doesn't seem to work, since I'd prefer to use function type 2 I'd like to know how to serve it to subprojects, I believe this must be possible but I can't find the right syntax. (question part 2)

I hope you guys can help me.


Solution

  • Your func1 is not a function, but you define a closure that you assign to a variable. In Groovy (which Gradle is based upon) you can call variable that has a closure assigned like it would be a function, but essentially it is not.

    So either use type one (you can also there use the optional type in the same place def func1 = { OptionalType param -> ...} but you don't need to as Groovy is dynamically typed.

    Or define your function with type 2 and then make a type 1 variable that calls the type 2 function.