Variadic Functions in Groovy

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

void sum(int... nums) {
    println "${nums.join(', ')} "
    int total = 0
    for (num in nums) {
        total += num
    }
    println total
}

Within the function, the type of nums is equivalent to an int[]. We can use standard array properties and methods on it like length and iteration.

Variadic functions can be called in the usual way with individual arguments.

sum(1, 2)
sum(1, 2, 3)

If you already have multiple args in an array, apply them to a variadic function using the spread operator (...) like this.

int[] nums = [1, 2, 3, 4]
sum(*nums)

Running the code will produce the following output:

[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10

Another key aspect of functions in Groovy is their ability to form closures, which we’ll look at next.