Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to spread a list inside a list in Kotlin?

Tags:

kotlin

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?

like image 799
Robin Trietsch Avatar asked Dec 21 '17 14:12

Robin Trietsch


People also ask

Does Kotlin have a spread operator?

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.

What is spread operator in Kotlin?

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)


2 Answers

The spread operator works on arrays, so you can do this:

listOf(1, 2, 3, *(arrayOf(4, 5, 6)))
like image 139
zsmb13 Avatar answered Oct 26 '22 00:10

zsmb13


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.

like image 36
s1m0nw1 Avatar answered Oct 26 '22 01:10

s1m0nw1