Emitting Java Lambdas in Groovy
In developing a Groovy library to be used with Java code, I want to be able to use Java Lambdas than Groovy specific mechanisms.
When accessing this library API from the Java side the user should not need any Groovy specific imports or expose any Groovy specifics features.
Java-specific Lambdas could be pass to the API and also Java-specific Lambdas should be returned from the API.
Is there a way that this can be achieved?
E.g.
def f() { return { n -> n + 1} }
The return type of f
is groovy.lang.Closure
. I want it to be Function
.
Also, instead of
def f(Closure c) { ... c.delegate = this c.resolveStrategy = DELEGATE_ONLY ... }
I want to replace Closure c
with Function
.
In doing so when using it from the Java side Groovy features and API are not exposed to the developer.
The short answer is that you will be able to do this just like in Java.
In java a lamda is accepted as an object that implements a functional interface – a functional interface being an interface that contains only a single abstract method which matches the signature of the lambda you will pass in.
As an example, you can use the Runnable interface which has just a run method with no parameters.
In groovy you will accept an object of type Runnable:
def myGroovyFunction(Runnable r) { r.run() }
You can use any functional interface here, for example something from java.util.function or your own interface.
your java code can now pass in a lambda like so:
MyGroovyClass.myGroovyFunction(() -> { System.out.println("This will be printed by the groovy function"); })