I have the following method. Its logic is very simple, if right is set then call left while it has a value (not null). When I write it in the following way, it works.
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
}
If, instead, I try to shorten the code using a do-while loop, it no longer smart casts next
to Node
. It shows this error:
Type mismatch.
Required: Node<T>
Found: Node<T>?
The code follows:
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
}