我有以下方法。它的邏輯非常簡單,如果設置了正確的值,那麼在它有一個值(非空值)時調用左邊的值。當我按照以下方式編寫它時,它會起作用。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