如何在Kotlin复制列表?
我使用
val selectedSeries = mutableListOf<String>()
selectedSeries.addAll(series)
有没有更简单的方法?
如何在Kotlin复制列表?
我使用
val selectedSeries = mutableListOf<String>()
selectedSeries.addAll(series)
有没有更简单的方法?
当前回答
I can come up with two alternative ways:
1. val selectedSeries = mutableListOf<String>().apply { addAll(series) }
2. val selectedSeries = mutableListOf(*series.toTypedArray())
更新:使用新的类型推断引擎(在Kotlin 1.3中可选),我们可以省略第一个例子中的泛型类型参数,并得到:
1. val selectedSeries = mutableListOf().apply { addAll(series) }
仅供参考。选择新推理的方法是kotlinc -Xnew-inference ./SourceCode。对于命令行,或者对于Gradle, kotlin {experimental {newInference 'enable'}。有关新的类型推断的更多信息,请查看此视频:KotlinConf 2018 -新的类型推断和相关语言特性,作者:Svetlana Isakova,特别是“30岁的构建器推理”
其他回答
我建议你做个肤浅的拷贝
.map{it}
这将适用于许多收集类型。
我将使用toCollection()扩展方法:
val original = listOf("A", "B", "C")
val copy = original.toCollection(mutableListOf())
这将创建一个新的MutableList,然后将原列表中的每个元素添加到新创建的列表中。
这里的推断类型是MutableList<String>。如果你不想暴露这个新列表的可变性,你可以显式地将该类型声明为一个不可变列表:
val copy: List<String> = original.toCollection(mutableListOf())
val selectedSeries = listOf(*series.toTypedArray())
I can come up with two alternative ways:
1. val selectedSeries = mutableListOf<String>().apply { addAll(series) }
2. val selectedSeries = mutableListOf(*series.toTypedArray())
更新:使用新的类型推断引擎(在Kotlin 1.3中可选),我们可以省略第一个例子中的泛型类型参数,并得到:
1. val selectedSeries = mutableListOf().apply { addAll(series) }
仅供参考。选择新推理的方法是kotlinc -Xnew-inference ./SourceCode。对于命令行,或者对于Gradle, kotlin {experimental {newInference 'enable'}。有关新的类型推断的更多信息,请查看此视频:KotlinConf 2018 -新的类型推断和相关语言特性,作者:Svetlana Isakova,特别是“30岁的构建器推理”
这很好。
val selectedSeries = series.toMutableList()