如何解决从CompletableFuture返回null为非null返回方法在Kotlin中例外地阻塞
我很惊讶下面的Kotlin代码编译。如果命中了异常块,我将返回null,并且该方法的签名不允许返回null。为什么编译器允许这样做?
suspend fun getRandomString(): String {
return httpClient.sendAsync(HttpRequest.newBuilder()
.uri(URI.create((baseUrl + "/getRandomString")).normalize())
.build(),BodyHandlers.ofString()).thenApply {
it.body().toUpperCase()
}.exceptionally {
log.error("could not retrieve a random string from the magical endpoint due to exception {}",it)
null
}.await()
}
解决方法
无视!这是由于CompletableFuture返回“ String!”,即平台类型。串!是(String还是String?),因此编译器允许它滑动。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。