Spread Operator
In this page:
Declaring a vararg Function
A parameter marked vararg accepts any number of individual arguments of that type, which are made available inside the function as an array.
Example: Declaring a vararg Function
fun sumAll(vararg numbers: Int): Int {
return numbers.sum()
}
fun main() {
println("Sum: ${sumAll(1, 2, 3, 4)}")
}
Login to try C/C++/Java/PHP code in the editor
Spreading an Array into vararg
When you already have an array and want to pass its contents as individual arguments to a vararg parameter, prefix it with * -- this is the spread operator.
Example: Spreading an Array into vararg
fun sumAll(vararg numbers: Int): Int {
return numbers.sum()
}
fun main() {
val values = intArrayOf(10, 20, 30)
println("Sum: ${sumAll(*values)}")
}
Login to try C/C++/Java/PHP code in the editor
Spreading a List
Since the spread operator works on arrays, a List must first be converted with .toTypedArray() before it can be spread into a vararg parameter.
Example: Spreading a List
fun joinAll(vararg words: String): String {
return words.joinToString(" ")
}
fun main() {
val wordList = listOf("Hello", "from", "Kotlin")
println(joinAll(*wordList.toTypedArray()))
}
Login to try C/C++/Java/PHP code in the editor
Combining Spread with Other Arguments
A spread array can be mixed with additional individual arguments in the same call, as long as the overall argument order still matches how the function expects them.
Example: Combining Spread with Other Arguments
fun sumAll(vararg numbers: Int): Int {
return numbers.sum()
}
fun main() {
val values = intArrayOf(1, 2, 3)
println("Sum: ${sumAll(0, *values, 100)}")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
*prefix when passing an array to avarargparameter, causing a type mismatch since a single array is not the same as several individual arguments. - Trying to spread a
Listdirectly; the spread operator works on arrays, so aListmust be converted with.toTypedArray()first. - Assuming spread can mix with other individual arguments incorrectly ordered; extra positional arguments before/after a spread must still respect parameter order rules.
- The
*(spread) operator unpacks an array into individual arguments for avarargparameter. - Without
*, passing an array directly to avarargparameter is a type mismatch. - A
Listmust first be converted to an array with.toTypedArray()before it can be spread. - Spread arguments can be combined with additional individual arguments in the same call.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: