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.
dodyg
December 19, 2012, 11:19pm
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.
geevee
December 20, 2012, 1:47pm
4
Currently, we automatically cast nullable values to not-null type only for local val s. For var this check must be more complex, because var s 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.
geevee
December 20, 2012, 7:41pm
6
I think the best solution for now is using "!!" operator.