Better null reference check?


#1

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.


#2

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.


#3

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.


#4

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.


#5

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.


#6

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