Kotlin ?.let + ?:运行 + CompletableFuture 意外行为
Kotlin ?.let + ?:run + CompletableFuture unexpected behaviour
这是代码,它按预期运行,没有异常
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
用于 运行 没有 return 值的任务,因此您得到 CompletableFuture<Void>
,并尝试使用 get
或 join
会给你 null
.
然后您将 join
的 null
结果作为您的 let
块的结果,这将导致您的 run
块被执行。
因为CompletableFuture.join()
return 空值原因
mayBeEmptyString?.let {
// println("Inside let")
CompletableFuture.runAsync{ println("Inside let")}.join()
}
将为空
run { }
将被执行
这是代码,它按预期运行,没有异常
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
用于 运行 没有 return 值的任务,因此您得到 CompletableFuture<Void>
,并尝试使用 get
或 join
会给你 null
.
然后您将 join
的 null
结果作为您的 let
块的结果,这将导致您的 run
块被执行。
因为CompletableFuture.join()
return 空值原因
mayBeEmptyString?.let {
// println("Inside let")
CompletableFuture.runAsync{ println("Inside let")}.join()
}
将为空
run { }
将被执行