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
我知道 left
是可变变量,但我明确检查 left != null
并且 left
是 类型Node
那么为什么不能将它智能转换为那种类型呢?
我怎样才能优雅地解决这个问题?
最佳答案
在执行 left != null
和 queue.add(left)
之间,另一个线程可能已将 left
的值更改为 null
.
要解决此问题,您有多种选择。以下是一些:
通过智能转换使用局部变量:
val node = left
if (node != null) {
queue.add(node)
}
使用 safe call例如以下之一:
left?.let { node -> queue.add(node) }
left?.let { queue.add(it) }
left?.let(queue::add)
使用 Elvis operator与 return
至return从封闭函数开始:
queue.add(left ?: return)
请注意,break
和 continue
可以类似地用于循环内的检查。
关于kotlin - 智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时本可以更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595529/