Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading