如何在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岁的构建器推理”
其他回答
你可以使用ArrayList构造函数:
这很好。
val selectedSeries = series.toMutableList()
以我之见,最好也是最常用的方法是在Kotlin(1.6+)的新版本中使用集合构建器。
val shallowListCopy = buildList { addAll(list) }
var oldList: List<ClassA>?
val newList = oldList.map { it.copy() }
val selectedSeries = listOf(*series.toTypedArray())