Array of strings in groovy
Solution 1
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()
Solution 2
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()
Lucas
Full stack software developer passionate about solving real world problems using my programming skills. Always learning new technologies, tools and ideas that help me to solve hard problems. Open to remote positions as software developer. Expertise: Java, JPA/Hibernate, JSF , Spring, SQL, MongoDB, NodeJs/Express.js Frontend: Angular, React, JavaScript, Typescript, html5, css
Updated on July 05, 2022Comments
-
Lucas almost 2 years
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?
-
tim_yates over 14 yearsor indeed ["lucas", "Fred", "Mary"] as String[]
-
Dónal over 14 yearsor
(String[])['Lucas', 'Fred', 'Mary']
-
Snekse over 9 yearsBut sometimes APIs require a String[], so providing both options in the answer would be nice.
-
Snekse over 9 yearsI think toArray() returns an Object[], not a String[].
-
The Unknown Dev over 8 yearsNice. 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!