59. Variable Arguments (Varargs)

There are times where we want to pass a variable number of parameters to the method. However, the parameter list for a method is fixed.

One approach is to use a list for a catch-all parameter, such as items does in the code below:

Using a list parameter
def buyGroceries(store, items) {
    println "I'm off to $store to buy:"
    for (item in items) {
        println "  -$item"
    }
}

buyGroceries 'The Corner Store', ['apples', 'cat food', 'cream']

Whilst the list path is an option, Groovy supports the use of variable arguments (varargs) using the “three-dot” (...) notation for the last (and only the last) parameter:

Using a varargs parameter
def buyGroceries(... items) {
    for (item in items) {
        println item
    }
}

buyGroceries 'apples', 'cat food', 'cream'

We can set a specific data type for the items parameter by placing the type before the ...:

Using a typed varargs parameter
def buyGroceries(String... items) {
    for (item in items) {
        println item
    }
}

buyGroceries 'apples', 'cat food', 'cream'

Let’s return to the first example in this chapter and rewrite it using varargs:

Varargs instead of a list
def buyGroceries(store, ... items) {
    println "I'm off to $store to buy:"
    for (item in items) {
        println "  -$item"
    }
}

buyGroceries 'The Corner Store', 'apples', 'cat food', 'cream'

So the items parameter is actually a list inside buyGroceries but the caller just passes a series of values to the method.