如何正确地将 java 集合转换为 Kotlin 语言

How to properly convert java collection to Kotlin language

我对kotlin collections很迷茫,尤其是看了官方文档,还是卡壳了。此外,如果我只是将粘贴 java 代码复制到 kotlin 文件中,自动转换的代码似乎不兼容。

List<List<command>> commandsList =
                commands.stream().map(this::rebuildCommand).collect(Collectors.toList());

这段代码,kotlin应该怎么写才正确?

复制粘贴给出

val commandsList: List<List<command>> = commands.stream().map(this::rebuildCommand).collect(Collectors.toList())

这是有效的 Kotlin 代码。如果你最终需要它成为一个 MutableList,你可以修改 return 类型,这样它就不会向上转换为只读的 Kotlin 列表:

val commandsList: MutableList<MutableList<command>> = commands.stream().map(this::rebuildCommand).collect(Collectors.toList())

如果您不需要它是可变的,那么在没有 Stream 和 Collector 的情况下这样做会更有效:

val commandsList: List<List<command>> = commands.map(this::rebuildCommand)