I would like to use the Groovy Closure class in a Java application, but am having more trouble than expected. Here's what I have:
int count = 0;
groovy.lang.Closure closure = { count = 1 };
However, when I try to compile this using JDK 7, I get the error: illegal initializer for Closure
Am I missing something really obvious? Thanks for your help.
We can pass a Closure as an argument to a method. Unary closures can use the implicit it parameter. We can assign a Closure to a variable and execute it later, either as a method or with call. Groovy determines the return type of the closures at runtime.
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope.
6) Mention what is the role of closure and listeners in Groovy? Groovy does not support anonymous inner classes; it is possible to determine action listeners inline through the means of closures. In Groovy, listeners closure are used as a ListenerAdapter where only one method of interest is overridden.
Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function.
There's already an answer above, I am simply adding an working example.
Groovy Code that accepts closure,
public class GroovyService {
Integer doSomething(Closure<Integer> fn) {
fn()
}
}
Calling groovy closure From java,
import groovy.lang.Closure;
public class JavaCanCallGroovy {
public static void main(String[] args) {
GroovyService service = new GroovyService();
Integer data = service.doSomething(new Closure<Integer>(null) { //need to pass owner = null
@Override
public Integer call() {
return 100;
}
});
System.out.println(data);
}
}
Call groovy closure from scala
import groovy.lang.Closure
object ScalaCanCallGroovy extends App {
private val closure = new Closure[Integer]() {
override def call() = 1
}
val groovyService = new GroovyService
val data = groovyService.doSomething(closure)
assert(data == 1)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With