Home > Software design >  Analog for operator :: in Kotlin
Analog for operator :: in Kotlin

Time:11-10

I can't fully understand how you can convert the code futuresList.stream().map(CompletableFuture::join).collect(Collectors.toList()) from Java to Kotlin code

I have a list of CompletableFuture and I want to combine for CompletableFuture.allOf

P.S. val futuresList : MutableList<CompletableFuture<String>>

CodePudding user response:

Your original code is almost a working one, you just need to specify the type parameter:

futuresList.stream().map(CompletableFuture<String>::join).collect(Collectors.toList())

Honestly, I'm not sure why this is required and why Kotlin does not use type inference in such a case. Alternatively, we can do it like this:

futuresList.stream().map { it.join() }.collect(Collectors.toList())

I believe this approach is more common in Kotlin.

Also, I'm not sure why do you use stream here. It seems the same as mapping the list directly:

futuresList.map { it.join() }

CodePudding user response:

Here's the kotlint code, which shows how to achieve what you want ...

fun main() {
    var newList = listOf(1, 2).map(Adder.Companion::addOne)
    newList.forEach { println(it) }
    // Will print 2, 3

}

class Adder {

    companion object {
        fun addOne(x: Int): Int {
            return x   1
        }
    }
}

Here's a working example.

  • Related