user572490
user572490

Reputation: 67

How to properly convert java collection to Kotlin language

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?

Upvotes: 0

Views: 131

Answers (1)

Tenfour04
Tenfour04

Reputation: 93551

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)

Upvotes: 1

Related Questions