Thursday, October 7, 2010

passing String array argument to a Groovy method

Let's say we have a Groovy method that takes a String array as an argument:

void myMethod(String[] arr) { ... }

When passing a string array to this method, the most intuitive way to do it is this:

myMethod(["a", "b", "c"])

However, this produces a NoSuchMethodError, because GDK converts ["a", "b", "c"] to an instance of ArrayList instead of String[]. Next thing you may try is this:

myMethod(new String[]{"a", "b", "c"})

, which is standard Java one-line syntax for creating a String array. This, however, also confuses GDK, and creates exception with this message:

No expression for the array constructor call

Groovy notices opening and closing braces and starts compiling it as a closure, which of course it isn't. This can be worked around in 2 ways:

myMethod(["a", "b", "c"] as String[])

or

myMethod((String[]) ["a", "b", "c"])

1 comment: