Kotlin 将列表转换为可变参数

Kotlin convert List to vararg

我有 List<UnitWithComponents>

类型的输入数据
class UnitWithComponents {
    var unit: Unit? = null
    var components: List<Component> = ArrayList()
}

我想将数据转换为 varargUnit

目前我正在做*data.map { it.unit!! }.toTypedArray()。有更好的方法吗?

不,这是正确的方法(假设您想要在 it.unitnull 时抛出列表中某些元素的异常)。

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

使用

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)

因此,在这种情况下,您应该替换:

发件人:strings = list.map { it }.toTypedArray()

收件人:*list.map { it }.toTypedArray()

GL

Source