Variadic Functions in Kotlin
On this page
Here’s how the variadic function example can be translated into Kotlin:
Example: Variadic Functions
Variadic functions can be called with any number of trailing arguments. For example, println
is a common variadic function.
Code Example
Here’s a function that will take an arbitrary number of Int
s as arguments.
Within the function, the type of nums
is equivalent to IntArray
. We can get its length using nums.size
, iterate over it with for
, and so on.
Running the Code
To run the above program, put the code in a Kotlin file and execute it with Kotlin compiler.
Variadic functions can be called in the usual way with individual arguments.
If you already have multiple arguments in an array, apply them to a variadic function using *
like this.
Another key aspect of functions in Kotlin is their ability to use higher-order functions and lambdas, which we’ll look at next.
Next example: Closures.