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循环来缩短代码,那么它就不再是智能强制转换next了Node.它显示了这个错误:
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)