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.

Get hands-on with 1200+ tech skills courses.