It is possible to do argument unpacking in Kotlin similar to how it is done in Python? E.g.
>>> a = [1,2,3]
>>> b = [*a,4,5,6]
>>> b
[1, 2, 3, 4, 5, 6]
I know that it is possible in Kotlin as follows:
>>> listOf(1, 2, 3, *listOf(4,5,6).toTypedArray())
[1, 2, 3, 4, 5, 6]
Feels like there is an easier way in Kotlin. Any ideas?
It's Kotlin's spread operator — the operator that unpacks an array into the list of values from the array. It is needed when you want to pass an array as the vararg parameter. it will fail with Type mismatch: inferred type is Array<String> but String was expected compilation error.
4. Spread Operator. Sometimes we have an existing array instance in Kotlin, and we want to pass it to a function accepting a vararg. In those situations, to decompose the array to a vararg, we can use the spread operator: val numbers = intArrayOf(1, 2, 3, 4) val summation = sum(*numbers) assertEquals(10, summation)
The spread operator works on arrays, so you can do this:
listOf(1, 2, 3, *(arrayOf(4, 5, 6)))
The python code can be expressed with the following Kotlin code. As already answered by zsmb13, the operator *
is also available in Kotlin:
fun main(args: Array<String>) {
val a = arrayOf(1, 2, 3)
val b = arrayOf(*a, 4, 5, 6)
println(b.contentToString())
}
Documentation tells us:
When we call a vararg-function, we can pass arguments one-by-one, e.g. asList(1, 2, 3), or, if we already have an array and want to pass its contents to the function, we use the spread operator (prefix the array with *):
Also related to this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With