The Kotlin compiler cannot understand that the variable is not NULL in the do-while loop

I have the following method. Its logic is very simple, if the correct value is given, then call left until it matters (but not empty). When I write it as follows, 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 with a do-while loop, it will no longer use smart next until Node . It shows this error:

 Type mismatch. Required: Node<T> Found: Node<T>? 

The following code:

 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 } 
+5
source share
1 answer

The compiler probably suggests that the following can be changed between an if statement and a loop from another thread. Since you can assure that the next one is not null, just add !! to the next when used in a loop: next !!

-1
source

Source: https://habr.com/ru/post/1273652/


All Articles