Reputation: 113
How can I declare a string array in Groovy? I am trying as below but it is throwing an error
def String[] osList = new String[]
No expression for the array constructor call at line:
What am i doing wrong?
Upvotes: 9
Views: 44207
Reputation: 20707
A simple way is
String[] osList = []
assert osList.class.array
assert 'java.lang.String[]' == osList.class.typeName
Another question is that this definition is rather useless. This is an immutable zero-length String[] and can be used only as a constant somewhere.
Upvotes: 5
Reputation:
First of: welcome to SO!
You have a few options for creating arrays in groovy.
But let's start with what you've done wrong.
def String[] osList = new String[]
You used both def
and String[]
here.
Def is an anonymous type, which means that groovy will figure out which type it is for you. String[] is the declared type, so what groovy will see here is:
String[] String[] osList = new String[]
which obviously won't work.
Arrays however need a fixed size, which needs to be given as an argument to the creation of the Array:
Type[] arr = new Type[sizeOfArray]
in your case if you'd want to have 10 items in the array you would do:
String[] osList = new String[10]
if you do not know how many Strings you will have, use a List instead. An ArrayList will do for this in most cases:
List<String> osList = new ArrayList<>()
now you can add items by calling:
osList.add("hey!")
or using groovy's list-add operator:
osList << "hey!"
For further issues you should refer to groovy's official documentation and see if you can't find the solution yourself!
Upvotes: 9
Reputation: 111
def arr = [] as String[]
or
String[] arr = [] as String[]
This should do it. You can test it and play around in here: https://groovyconsole.appspot.com/
Upvotes: 7