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?
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)
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) }
The task will be asynchronously completed running in given Executor and finally supplyAsync () will return new CompletableFuture with the value obtained by calling given Supplier. Find the sample code for supplyAsync () with Executor .
We need to pass a Supplier as a task to supplyAsync () method. The task will be asynchronously completed running in given Executor and finally supplyAsync () will return new CompletableFuture with the value obtained by calling given Supplier. Find the sample code for supplyAsync () with Executor .
Kotlin's approach to working with asynchronous code is using coroutines, which is the idea of suspendable computations, i.e. the idea that a function can suspend its execution at some point and resume later on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With