我有以下方法 . 它的逻辑很简单,如果设置了right,那么当它有一个值(非null)时调用left . 当我用以下方式编写它时,它可以工作 .
fun goNext(from: Node): Node? {
var prev : Node = from
var next : Node? = from.right
if (next != null) {
prev = next
next = next.left
while (next != null) {
prev = next
next = next.left
}
}
return prev
}
相反,如果我尝试使用do-while循环缩短代码,则不再智能地将 next
强制转换为 Node
. 它显示了这个错误:
Type mismatch.
Required: Node<T>
Found: Node<T>?
代码如下:
fun goNext(from: Node): Node? {
var prev : Node = from
var next : Node? = from.right
if (next != null) {
do {
prev = next // Error is here, even though next can't be null
next = next.left
} while (next != null)
}
return prev
}
1 回答
编译器可能假定next语句可以在if语句和来自另一个线程的循环之间进行更改 . 既然你可以保证next不是null,那就加!!下一次在循环中使用它时:下一个!!