Junior
What is the 'spread' operator in Kotlin and how to use it?
sobes.tech AI
Answer from AI
The 'spread' operator in Kotlin corresponds to the prefix * before an array or vararg. It is used to pass the elements of such a collection to a function expecting a variable number of arguments (vararg). Essentially, it "spreads" the collection into individual arguments.
Example of usage:
fun printNumbers(vararg numbers: Int) {
for (number in numbers) {
println(number)
}
}
fun main() {
val intArray = intArrayOf(1, 2, 3)
printNumbers(*intArray) // Using the spread operator
}
Without the * operator, attempting to pass intArray to printNumbers would result in a compilation error, as printNumbers expects a variable number of Int, not an Int array.
The 'spread' operator can also be used when creating a new array by combining an existing array with individual elements or other arrays:
fun main() {
val array1 = arrayOf(1, 2)
val array2 = arrayOf(3, 4)
val combinedArray = arrayOf(*array1, 5, *array2) // Using the spread operator
println(combinedArray.contentToString()) // Outputs [1, 2, 5, 3, 4]
}
Key points:
- Applied only to arrays (
Array, primitive arrays) andvararg. - Spreads the collection's elements into separate function arguments or elements of a new array.
- Denoted with the prefix
*.