智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改 [英] Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time
问题描述
Kotlin 新手问,为什么下面的代码不能编译?":
var left:节点?= 空有趣的表演(){如果(左!= null){queue.add(left)//此处出错}}
<块引用>
智能转换到 'Node' 是不可能的,因为 'left' 是可变的这个时候可能已经改变的属性
我知道 left
是可变变量,但我明确检查了 left != null
和 left
是 类型Node
那么为什么不能将其智能转换为该类型?
我该如何优雅地解决这个问题?
在执行 left != null
和 queue.add(left)
之间,另一个线程可能已经改变left
到 null
的值.
要解决此问题,您有多种选择.这里有一些:
在智能转换中使用局部变量:
val 节点 = 左如果(节点!= null){queue.add(节点)}
使用安全调用,例如以下内容:
left?.let { node ->队列.添加(节点)}left?.let { queue.add(it) }left?.let(queue::add)
使用 Elvis operator 和
return
到 返回 早于封闭函数:queue.add(left ?: return)
请注意,
break
和continue
可以类似地用于循环内的检查.
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
}
}
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?
How can I fix this elegantly?
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)
Note that
break
andcontinue
can be used similarly for checks within loops.
这篇关于智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!