Variadic Functions in Kotlin

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 Ints as arguments.

fun sum(vararg nums: Int) {
    println(nums.joinToString(" "))
    var total = 0
    for (num in nums) {
        total += num
    }
    println(total)
}

fun main() {
    sum(1, 2)
    sum(1, 2, 3)
    val nums = intArrayOf(1, 2, 3, 4)
    sum(*nums)
}

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.

$ kotlinc variadic-functions.kt -include-runtime -d variadic-functions.jar
$ java -jar variadic-functions.jar
[1, 2] 3
[1, 2, 3] 6
[1, 2, 3, 4] 10

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.