Kotlin 中 CompletableFuture 异常方法的使用

Joh*_*nny 5 kotlin completable-future kotlin-interop

我正在尝试处理 Kotlin 中的 CompletableFuture 异常,但我无法弄清楚如何提供适当的参数。所以,例如,我有:

CompletableFuture.runAsync { "sr" } .exceptionally{e -> {}}

但随后编译器抱怨Cannot infer type parameter T

我该如何解决?

Grz*_*rek 5

一个相当棘手的案例,由于一些 Kotlin 魔法而变得棘手:)

您的问题的直接解决方案是以下代码:

CompletableFuture.runAsync {"sr"}
   .exceptionally({e -> null})
Run Code Online (Sandbox Code Playgroud)

详细解释在这里:

runAsync方法接受 aRunnable这意味着执行后它将返回Void。传递给exceptionallymethod的函数必须与 the 的泛型参数匹配,CompletableFuture因此在这种特殊情况下,您需要通过null显式返回来帮助编译器。

因此,以下内容将毫无问题地编译:

CompletableFuture.runAsync {"sr"}
 .exceptionally({null})

CompletableFuture.runAsync {}
 .exceptionally({null})
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,“sr”字符串将被简单地忽略并且不会返回,因为它runAsync接受 a Runnable

你可能想做这样的事情:

 CompletableFuture.supplyAsync {"sr"}
   .exceptionally({"sr_exceptional"})
Run Code Online (Sandbox Code Playgroud)

或者:

CompletableFuture.supplyAsync {"sr"}
  .exceptionally({e -> "sr_exceptional"})
Run Code Online (Sandbox Code Playgroud)