Dreamer
Dreamer

Reputation: 35

Groovy Array of Strings

I know curly brackets are not used to initialize array in Groovy but I have noticed one peculiar thing.

Why groovy doesn't give compiler error when I initialize an array like this.

String emailAddress = "[email protected]";

String [] var = {emailAddress};

println var[0];

Output: com.test.examples.GroovyTest$_main_closure1@12e4860e

When I try to declare like this I get error:

String [] var = {"a","b"};

Can anybody explain this?

Upvotes: 0

Views: 3864

Answers (1)

tim_yates
tim_yates

Reputation: 171054

When you do:

String [] var = {emailAddress};

That creates a Closure that returns a String emailAddress, and then crams that closure into a String array (by calling toString() on it), as that's what you told it to do ;-)

So var equals ['ConsoleScript0$_run_closure1@60fd82c1'] (or similar, depending on where you're running things)

When you do:

String [] var = {"a","b"};

The right-hand side is not a valid Closure, so the script fails to parse.

What you want is:

String[] var = ['a', 'b']

Or:

String[] var = [emailAddress]

Upvotes: 6

Related Questions