Home > Net >  How to properly convert java collection to Kotlin language
How to properly convert java collection to Kotlin language

Time:10-12

I'm pretty confused about kotlin collections, especially after reading official documents, I'm still got stuck. Besides, if I just copy paste java code into kotlin file, the auto-converted code seems not compatible.

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

For this piece of code, how should I correctly write it in kotlin?

CodePudding user response:

Copy-pasting gives

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

Which is valid Kotlin code. If you need it to be a MutableList in the end, you can modify the return type so it isn't upcasting to the read-only Kotlin List:

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

If you don't need it to be mutable, it's more efficient to do this without a Stream and Collector:

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