75

In ruby, there is a indiom to create a array of strings like this:

names = %w( lucas Fred Mary )

Is there something like that in groovy?

2 Answers 2

137

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()
Sign up to request clarification or add additional context in comments.

4 Comments

or indeed ["lucas", "Fred", "Mary"] as String[]
or (String[])['Lucas', 'Fred', 'Mary']
I think toArray() returns an Object[], not a String[].
It's been a year since this comment was first published, but yes, toArray() returns an array of objects. The longer, uglier version of the method is needed to return a typed array: toArray(new String[0]);
65

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

2 Comments

But sometimes APIs require a String[], so providing both options in the answer would be nice.
Nice. I was actually looking to make an array, convert to list and then check if it contains a string, but I can skip the middle part by just creating the list directly and calling contains(). That's Groovy!

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.