Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - expanding list into closure arguments

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?

like image 983
Roy Truelove Avatar asked May 08 '12 21:05

Roy Truelove


People also ask

How do you make a closure on Groovy?

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.

What does [] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What is the use of closure in Groovy?

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.

What is inject in Groovy?

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.


1 Answers

Does:

c.call( *args )

Work? Not at a computer atm to test it

like image 121
tim_yates Avatar answered Sep 27 '22 23:09

tim_yates