i具有以下方法。它的逻辑非常简单,如果设置右,则在其具有值(而不是null)的同时向左调用。当我以以下方式编写它时,它可以正常工作。
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-lile循环缩短代码,它不再智能将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
}
编译器可能假定可以在if语句和循环之间从另一个线程更改下一个。由于您可以确保接下来不是零,只需添加!下一个在循环中使用它时:next !!