从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?),因此编译器允许它滑动。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...