Kotlin编译器不能确定该variables在do-while循环中是不可空的
我有以下方法。 它的逻辑非常简单,如果设置了权限,那么在有值的时候调用左边(非空值)。 当我以下面的方式写它,它的工作。
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循环缩短代码,那么它不再是在Node
next
智能代码。 它显示这个错误:
Type mismatch. Required: Node Found: Node?
代码如下:
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。 既然你可以保证下一个不是null,只需加上!! 到下一个在循环中使用它时:next!