5

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
}
barsdeveloper
  • 930
  • 8
  • 28

1 Answers1

-1

The compiler probably assumes that next can be changed between the if statement and the loop from another thread. Since you can assure that next is not null, just add !! to next when using it in the loop: next!!

Zonico
  • 192
  • 1
  • 11