我有以下方法。它的逻辑非常简单,如果设置了正确的值,那么在它有一个值(非空值)时调用左边的值。当我按照以下方式编写它时,它会起作用。Kotlin编译器无法确定该变量在可执行循环中是不可空的
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
}
为什么不简化为只是'while(next!= null){...}'? –
你是对的!我没有看到它。 – biowep