Pierre :
I'm new to groovy/gradle As far as I understand gradle/groovy is compatible with java.
I wrote the following gradle (without any task) in a 'build.gradle' file:
def myFun = {->"Hello World"}
class MyClass {
String getLabel() {
return ""+ myFun();
}
}
System.err.println(new MyClass().getLabel());
where a class MyClass
calls the 'global'(?) function myFun
.
Calling gradle --tasks
produces the following error:
FAILURE: Build failed with an exception.
* Where:
Build file 'build.gradle' line: 6
* What went wrong:
A problem occurred evaluating root project 'tmp'.
> No signature of method: MyClass.myFun() is applicable for argument types: () values: []
Possible solutions: find(), find(groovy.lang.Closure), wait(), any(), every(), dump()
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 2.671 secs
How can I make this class MyClass
to 'see' the function myFun
?
Thank you.
nickb :
You can't directly, since there are no global variables in Groovy. You can modify your declaration to pass an instance of the current class so you can invoke the myFun
closure:
@groovy.transform.Field
def myFun = {-> "Hello World"}
class MyClass {
String getLabel(script) {
return ""+ script.myFun();
}
}
System.err.println(new MyClass().getLabel(this))
Or you can use the binding
object, but it's the same pattern.
For more info: