Reputation: 22456
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?
Upvotes: 8
Views: 3154