Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of CompletableFuture's exceptionally method in Kotlin

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?

like image 374
Johnny Avatar asked Nov 14 '16 16:11

Johnny


People also ask

What is exceptionally in CompletableFuture?

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.

Why we use CompletableFuture?

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.

Can CompletableFuture throw exception?

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.

How Completable Future works?

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.


1 Answers

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"})
like image 154
Grzegorz Piwowarek Avatar answered Oct 06 '22 01:10

Grzegorz Piwowarek