问题描述
Kotlin新手问,为什么下面的代码不能编译?":
And the Kotlin newbie asks, "why won't the following code compile?":
var left: Node? = null
fun show() {
if (left != null) {
queue.add(left) // ERROR HERE
}
}
我知道left
是可变变量,但是我明确检查了left != null
并且left
是Node
类型,所以为什么不能将其智能转换为该类型?
I get that left
is mutable variable, but I'm explicitly checking left != null
and left
is of type Node
so why can't it be smart-casted to that type?
如何解决这个问题? :)
How can I fix this elegantly? :)
推荐答案
在执行left != null
和queue.add(left)
之间,另一个线程可能已将left
的值更改为null
.
Between execution of left != null
and queue.add(left)
another thread could have changed the value of left
to null
.
要解决此问题,您有几种选择.这里是一些:
To work around this you have several options. Here are some:
-
使用局部变量进行智能强制转换:
Use a local variable with smart cast:
val node = left
if (node != null) {
queue.add(node)
}
使用安全呼叫,例如一个以下:
Use a safe call such as one of the following:
left?.let { node -> queue.add(node) }
left?.let { queue.add(it) }
left?.let(queue::add)
Use the Elvis operator with return
to return early from the enclosing function:
queue.add(left ?: return)
请注意,break
和continue
可以类似地用于循环内的检查.
Note that break
and continue
can be used similarly for checks within loops.
这篇关于无法将类型强制转换为“类型",因为“变量"是可变属性,到那时可能已经更改了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!