CompletableFuture 的 exceptionally 方法在 Kotlin 中的使用
Usage of CompletableFuture's exceptionally method in Kotlin
我正在尝试在 Kotlin 中处理 CompletableFuture 异常,但我无法弄清楚如何提供适当的参数。因此,例如,我有:
CompletableFuture.runAsync { "sr" }
.exceptionally{e -> {}}
但随后编译器报错 Cannot infer type parameter T
。
我该如何解决这个问题?
一个非常棘手的案例,由于一些 Kotlin 魔法而变得棘手:)
您的问题的直接解决方案是以下代码:
CompletableFuture.runAsync {"sr"}
.exceptionally({e -> null})
详细解释在这里:
runAsync
方法接受一个 Runnable
,这意味着执行后它将 return Void
。传递给 exceptionally
方法的函数必须匹配 CompletableFuture
的通用参数,因此在这种特殊情况下,您需要通过 returning null
显式帮助编译器。
所以下面的编译没有问题:
CompletableFuture.runAsync {"sr"}
.exceptionally({null})
CompletableFuture.runAsync {}
.exceptionally({null})
在第一种情况下,"sr" 字符串将被简单地忽略而不是 returned,因为 runAsync
接受 Runnable
.
您可能想做类似的事情:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({"sr_exceptional"})
或:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({e -> "sr_exceptional"})
我正在尝试在 Kotlin 中处理 CompletableFuture 异常,但我无法弄清楚如何提供适当的参数。因此,例如,我有:
CompletableFuture.runAsync { "sr" }
.exceptionally{e -> {}}
但随后编译器报错 Cannot infer type parameter T
。
我该如何解决这个问题?
一个非常棘手的案例,由于一些 Kotlin 魔法而变得棘手:)
您的问题的直接解决方案是以下代码:
CompletableFuture.runAsync {"sr"}
.exceptionally({e -> null})
详细解释在这里:
runAsync
方法接受一个 Runnable
,这意味着执行后它将 return Void
。传递给 exceptionally
方法的函数必须匹配 CompletableFuture
的通用参数,因此在这种特殊情况下,您需要通过 returning null
显式帮助编译器。
所以下面的编译没有问题:
CompletableFuture.runAsync {"sr"}
.exceptionally({null})
CompletableFuture.runAsync {}
.exceptionally({null})
在第一种情况下,"sr" 字符串将被简单地忽略而不是 returned,因为 runAsync
接受 Runnable
.
您可能想做类似的事情:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({"sr_exceptional"})
或:
CompletableFuture.supplyAsync {"sr"}
.exceptionally({e -> "sr_exceptional"})