Kotlin Vararg Parameters in Functions Spread Operator: Passing arrays into vararg functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Arrays can be passed into vararg functions using the Spread Operator, *.

Assuming the following function exists...

fun printNumbers(vararg numbers: Int) {
    for (number in numbers) {
        println(number)
    }
}

You can pass an array into the function like so...

val numbers = intArrayOf(1, 2, 3)
printNumbers(*numbers)

// This is the same as passing in (1, 2, 3)

The spread operator can also be used in the middle of the parameters...

val numbers = intArrayOf(1, 2, 3)
printNumbers(10, 20, *numbers, 30, 40)

// This is the same as passing in (10, 20, 1, 2, 3, 30, 40)


Got any Kotlin Question?