问题描述
这是代码,它按预期运行,没有异常
fun main() {
var mayBeEmptyString: String?
mayBeEmptyString = "1";
mayBeEmptyString?.let {
println("Inside let")
} ?: run {
throw RuntimeException("Inside run")
}
}
输出:
Inside let
这是我无法理解其工作方式的代码:
fun main() {
var mayBeEmptyString: String?
mayBeEmptyString = "1";
mayBeEmptyString?.let {
// println("Inside let")
CompletableFuture.runAsync{ println("Inside let")}.join()
} ?: run {
throw RuntimeException("Inside run")
}
}
输出:
Inside let
Exception in thread "main" java.lang.RuntimeException: Inside run
at com.test.TestKt.main(test.kt:15)
at com.test.TestKt.main(test.kt)
有人可以解释这里发生了什么吗?谢谢。
解决方法
runAsync
用于运行不返回值的任务,因此您得到CompletableFuture<Void>
,并尝试使用get
或join
读取其值会给你null
。
然后将null
的{{1}}结果作为join
块的结果,这将导致您的let
块被执行。
因为CompletableFuture.join()
返回空值原因
mayBeEmptyString?.let {
// println("Inside let")
CompletableFuture.runAsync{ println("Inside let")}.join()
}
将为空
并且run { }
将被执行