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:
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:
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 ...:
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:
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.