jkratz55
jkratz55

Reputation: 881

Kotlin supplyAsync with executor

I want to create a CompletableFuture with a return value that runs on a specific executor in Kotlin.

The following code works just fine.

return CompletableFuture.supplyAsync {
        val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
        commandHandler.handle(command)
 }

However when I attempt to pass the executor it won't compile.

return CompletableFuture.supplyAsync({
        val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
        commandHandler.handle(command)
}, exec)

I tried to get clever and wrote the Java version and had Intellij covert it to Kotlin, but that one had the same error as well. What am I doing wrong here?

enter image description here

EDIT:

I can make it work by doing the following but it seems unnecessary. Can someone explain why this works but other methods do not. Are there other ways to write this code?

return CompletableFuture.supplyAsync(Supplier {
    commandHandler.handle(command)
}, exec) 

Upvotes: 5

Views: 3333

Answers (1)

Rene
Rene

Reputation: 6148

I do not exactly know, why it is not working. But the following does work:

return CompletableFuture.supplyAsync({
    val commandHandler = registry.get<TCommand, TResponse>(command::class.java)
    commandHandler.handle(command)
}, exec::execute)

As you can see, I changed the second parameter to a method reference. Now the signature of the method is:

supplyAsync(supplier: () -> U, executor: (Runnable)-> Unit)

If you pass the Executor directly, Kotlin chooses the signature:

supplyAsync(supplier: Supplier<U>, executor: Executor)

It looks like you can not mix interface and lambda style.

Upvotes: 6

Related Questions