Search code examples
groovy

How to declare a string array in Groovy?


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?


Solution

  • 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!