Kotlin编译器无法弄清楚变量在do-while循环中不可为空

bar*_*-md 5 null nullable do-while kotlin

我有以下方法.它的逻辑很简单,如果设置了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
}
Run Code Online (Sandbox Code Playgroud)

相反,如果我尝试使用do-while循环来缩短代码,那么它就不再是智能强制转换nextNode.它显示了这个错误:

Type mismatch.
Required: Node<T>
Found: Node<T>?
Run Code Online (Sandbox Code Playgroud)

代码如下:

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
}
Run Code Online (Sandbox Code Playgroud)

Zon*_*ico -1

编译器可能假设 next 可以在 if 语句和另一个线程的循环之间进行更改。由于您可以确保 next 不为空,因此只需添加 !! 在循环中使用它时到下一个:下一个!