27

I have input data of type List<UnitWithComponents>

class UnitWithComponents {
    var unit: Unit? = null
    var components: List<Component> = ArrayList()
}

I want to convert the data to a vararg of Unit

Currently I am doing *data.map { it.unit!! }.toTypedArray(). Is there a better way to do it?

Jack Guo
  • 3,959
  • 8
  • 39
  • 60

2 Answers2

23
fun foo(vararg strings: String) { /*...*/ }

Using

foo(strings = arrayOf("a", "b", "c"))

val list: MutableList<String> = listOf("a", "b", "c") as MutableList<String>
foo(strings = list.map { it }.toTypedArray())

Named arguments are not allowed for non-Kotlin functions (*.java)

So, in this case you should replace:

From: strings = list.map { it }.toTypedArray()

To: *list.map { it }.toTypedArray()

GL

Source

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
  • There is no need to use `as MutableList` here, and in some cases that will cause a crash because not all overloads of the `listOf` function in the standard library use MutableList under the hood. – Tenfour04 Sep 15 '22 at 14:24
6

No, that's the correct way to do it (assuming you want to throw an exception when it.unit is null for some element of the list).

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487