Better null reference check?

Sorry if this has been asked before - am new to Kotlin.

I have some code like this:

fun list(start: SomeObject) {
  var e = start
  while ( e != null ) {
          e.doSomething()
          e = e.next()
  }
}

This currently gives a compiler error because ‘e’ is nullable, but this code can never cause an NPE, so shouldn’t this be allowed?

Thanks!
Alfie.

Sorry in my actual code e is declared as:

var e : SomeObject?

Otherwise compiler gives error on e.next() if the next function has a nullable return.

Alfie.

change the variable declaration from var to val and it will work. The compiler cannot be sure that you haven't nullify that var after the null check.

Currently, we automatically cast nullable values to not-null type only for local vals. For var this check must be more complex, because vars can have modifications and can be captured in closure. We are planning to do it later, I have added feature request for it: KT-3175.

Thanks a lot for the reply - good to know that it's something possible/planned.

Is there another more Kotlin-esque pattern that can be used for this kind of loop?

Regards, Alfie.

I think the best solution for now is using "!!" operator.