Notnull assertion issue

The following code works as expected (ie it produces a runtime error)

    var qq:String? = null
    println(qq!!.length)	//This produces a runtime NullPointerException

But the following code does not compile. It complains that length does not exist.

    var qq:String? 
    qq = null
    println(qq!!.length)	//This produces a compilation error

I can’t figure out why the compiler is happy with the first case, but not the second.

1 Like

The first is like casting null (actually: Nothing?) to String?. The second is smart-casting String? to null/Nothing?.

I must say I’m not a huge fan of the first behavior, I would prefer it to work the same as 2.

1 Like

I’m recently coming to writing this as:

    qq?.let {
        println(it.length)
    }

Those two are not the same, they will result in different behavior.