11

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?

3

3 Answers 3

10

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think it is the case that our compiler (or runtime) sees def String[] osList = new String[] as String[] String[] osList = new String[]. Assuming you specify a size, def String[] osList = new String[0] is not seen as String[] String[] osList = new String[0]. The former is valid (though non-sensical) but the latter is invalid, and shouldn't compile.
7
​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/

1 Comment

I think if you use either of those approaches, the array will always be empty, and there will be no way to put anything in the array.
5

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.

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.