Spread Operator Passing arrays into vararg functions
suggest changeArrays 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)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents