Spread Operator Passing arrays into vararg functions

suggest change

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents