Is it possible to have a list and use it as an argument for a closure signature that instead several variables? The reason is that I have to call a closure from java code, and the java code won't know what variables the groovy closure needs.
This is better served with an example.
Say I have a 'closure repository', where each closure might have different signatures. EG:
closures = [
closureA: { int a, String b ->
a.times {
System.err.println(b);
}
},
closureB: { int a, int b, String c ->
(a+b).times {
System.err.println(c);
}
}
]
Then I've got a method that I'm exposing to my java code to call these closures:
def tryClosureExpansion(String whichClosure, Object ... args) {
def c = closures[whichClosure]
c.call(args) // DOESNT COMPILE !
}
And it Java I'd call this method like this:
// these calls will happen from Java, not from Groovy
tryClosureExpansion("closureA", 1, "Hello");
tryClosureExpansion("closureB", 1, 5, "Hello more");
See above on the line that doesn't compile. I feel like groovy is 'groovy' enough to handle something like this. Any alternative that might fly?
Defining a closure. Where [closureParameters->] is an optional comma-delimited list of parameters, and statements are 0 or more Groovy statements. The parameters look similar to a method parameter list, and these parameters may be typed or untyped.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
A closure is an anonymous block of code. In Groovy, it is an instance of the Closure class. Closures can take 0 or more parameters and always return a value. Additionally, a closure may access surrounding variables outside its scope and use them — along with its local variables — during execution.
Inject is the groovy way to do a left fold. Left fold is basically iterating over a list from the head and applying a function to the current element and the accumulated value.
Does:
c.call( *args )
Work? Not at a computer atm to test it
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