26

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?

Robin Trietsch
  • 1,662
  • 2
  • 19
  • 31
  • 3
    If `a = arrayOf(4, 5, 6)`, then `b = listOf(1, 2, 3, *a)` works just fine; see e.g. https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs – jonrsharpe Dec 21 '17 at 15:00

2 Answers2

36

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

listOf(1, 2, 3, *(arrayOf(4, 5, 6)))
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • 22
    Any reason why the spread operator is not implemented for other types of collections? – jivimberg Jun 29 '18 at 02:43
  • 10
    If you're just adding to the beginning or end, you can also just add the lists: `listOf(1,2,3) + listOf(4,5,6)` – cs_pupil Mar 04 '20 at 17:03
  • Yeah, it's a bit of an unfortunate limitation in Kotlin. You can spread lists or whatever with the equivalent operator in Scala, for example. – Matt R May 27 '20 at 10:42
  • @MattR Scala is so much better than Kotlin but Android adopting Kotlin and gradle adopting Kotlin & Groovy effectively killed any chance of Scala becoming the mainstream "modern JVM language". Sad. – aeskreis Jun 10 '22 at 18:54
3

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196