I'm trying to handle CompletableFuture exceptions in Kotlin, but I'm not able to figure out how to supply the appropriate parameters. So, for example, I have:
CompletableFuture.runAsync { "sr" }
.exceptionally{e -> {}}
but then the compiler complains Cannot infer type parameter T
.
How do I fix this?
exceptionally. public CompletableFuture<T> exceptionally( Function<Throwable, ? extends T> fn) { ... } In method exceptionally() , you only have access to the exception and not the result. Because as the method name indicates, the method only handles exceptional cases: when an exception happened.
CompletableFuture is used for asynchronous programming in Java. Asynchronous programming is a means of writing non-blocking code by running a task on a separate thread than the main application thread and notifying the main thread about its progress, completion or failure.
The CompletableFuture. join() method is similar to the get method, but it throws an unchecked exception in case the Future does not complete normally. This makes it possible to use it as a method reference in the Stream. map() method.
What is CompletableFuture? A CompltableFuture is used for asynchronous programming. Asynchronous programming means writing non-blocking code. It runs a task on a separate thread than the main application thread and notifies the main thread about its progress, completion or failure.
Quite a tricky case which becomes tricky because of some Kotlin magic :)
The direct solution to your problem would be the following code:
CompletableFuture.runAsync {"sr"}
.exceptionally({e -> null})
The detailed explanation goes here:
The runAsync
method accepts a Runnable
which means after execution it will return Void
. The function passed to exceptionally
method must match the generic parameter of the CompletableFuture
so in this particular case, you need to help a compiler by returning null
explicitly.
So the following will compile without problems:
CompletableFuture.runAsync {"sr"}
.exceptionally({null})
CompletableFuture.runAsync {}
.exceptionally({null})
In the first case, the "sr" String will simply be ignored and not returned since the runAsync
accepts a Runnable
.
You probably wanted to do something like:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({"sr_exceptional"})
or:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({e -> "sr_exceptional"})
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