问题:
And the Kotlin newbie asks, "why won't the following code compile?": Kotlin 新手会问,“为什么下面的代码不能编译?”:
var left: Node? = null
fun show() {
if (left != null) {
queue.add(left) // ERROR HERE
}
}
Smart cast to 'Node' is impossible, because 'left' is a mutable property that could have been changed by this time智能转换到“节点”是不可能的,因为“左”是一个可变属性,此时可能已经改变
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?我知道left
是可变变量,但我明确检查left != null
并且left
是Node
类型,所以为什么不能将它智能转换为该类型?
How can I fix this elegantly?我该如何优雅地解决这个问题?
解决方案:
参考一: https://en.stackoom.com/question/317Kj参考二: https://stackoom.com/question/317Kj