Groovy - expanding list into closure arguments

closures, dynamic-programming, groovy

Solution

Does:

c.call( *args )

Work? Not at a computer atm to test it

Problem

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?

Original source