Search code examples
groovy

How to call a Groovy Closure with an Object Array


I may be misunderstanding how to use varargs, but according to the Groovy Docs for Closures, for the function public V call(Object... args) , the arguments parameter "could be a single value or a List of values".

But when I try to do something like this:

Closure myClosure = { arg1, arg2, arg3 ->
    println arg1 == null
    println arg2 == null
    println arg3 == null
}
 Object[] argsArray = new Object[]{"John", "Jack", "Mack"}
 myClosure.call(argsArray)

The compiler throws an groovy.lang.MissingMethodException: No signature of method: .call() is applicable for argument types: ([Ljava.lang.Object;)

I couldn't even get the varargs function to work when passing in an actual varargs either.

def myVarargsFunction(Object... args){
    println "myVarargsFunction"
    myClosure.call(args)
}

This code results in the same error (After I change the scope of Closure myClosure of course). I don't under stand why either or these situations do not work. I know there are other ways to get this to work, I just want to understand why this doesn't work.


Solution

  • You can use the spread operator:

        myClosure.call(*args)