Kotlin non-null assertion with safe operator

Viewed 89

Why this code is giving me the NPE error?

fun main() {
    val myObj: MyObj? = null
    print(myObj?.someVal!!)
}

class MyObj{
    val someVal = 1
}

Does non-null assertion evaluate the whole expression before? I thought that myObj? should be enough to print null here.

2 Answers

Yes. When you use a null-safe call, the expression is evaluated to null if the receiver is null, so

myObj?.someVal!!

behaves the same as

(if (myObj != null) myObj.someVal else null)!!

(If myObj is a property rather than local variable, these aren't equivalent, since smart-casting wouldn't work.)

Simple example:

This code will print null:

fun main() {
    val myObj: MyObj? = null
    val someVal = myObj?.someVal
    print(someVal)
}

This code will throw NPE as the variable is null:

fun main() {
    val myObj: MyObj? = null
    val someVal = myObj?.someVal
    print(someVal!!)
}
Related