vararg and Spread

Functions like println() take a variable number of arguments. The vararg feature of Kotlin provides a type-safe way to create functions that can receive a variable number of arguments. The spread operator is useful to explode or spread values in a collection as discrete arguments. We’ll look at vararg first and spread next.

Variable number of arguments

In Functions with Block Body, we wrote a max() function that took an array of numbers. In the call to the function, as expected, we passed an array of values. If we already have an array of values, then it’s not a big deal; but if we have a discrete set of values, then to call the function we’ll have to create a temporary array of those values and then pass that array. Tedious.

In Kotlin, functions may take a variable number of arguments. Let’s convert the max() function to be more flexible for the caller.

Press + to interact
fun max(vararg numbers: Int): Int {
var large = Int.MIN_VALUE
for (number in numbers) {
large = if (number > large) number else large
}
return large
}

Compared to the max() function we wrote previously, this version has two changes, both in the parameter list. First, the parameter numbers is prefixed with the keyword vararg. Second, the type of the parameter is specified ...