0

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?

1 Answer 1

6

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.