6

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?

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
Johnny
  • 7,073
  • 9
  • 46
  • 72

1 Answers1

6

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"})
Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93