从CompletableFuture返回null为非null返回方法在Kotlin中例外地阻塞

时间:2020-08-12 01:21:49

标签: kotlin completable-future

我很惊讶下面的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()
}

1 个答案:

答案 0 :(得分:-1)

无视!这是由于CompletableFuture返回“ String!”,即平台类型。串!是(String还是String?),因此编译器允许它滑动。