简体   繁体   中英

Kotlin: Unresolved reference while simulating NPE

I am new to Kotlin and I am trying some practice programs.
When I am trying to simulate NPE using:! operator but my program throws below error:

Kotlin: Unresolved reference: length

I took the program reference from here

And my program is:

fun main(args: Array<String>){
    var b: String? = "Hello"     // variable is declared as nullable
    var blen = b!!.length
    println("b is : $b")
    println("b length is : $blen")

    b = null
    println("b is : $b")
    blen = b!!.length // <-- Here is the error
    println("b length is : $blen")
}

I am expecting NullPointerException in this code.
Any idea what is wrong here?

PS: I have already seen similar questions - this or this but nothing relevant I found.

The compiler is smart enough in this case to see that b is always null in this exact place. So it can in theory smart cast b to the type Nothing? (a type holding only the null value).

Not sure if it actually does, but if it did, then it would be natural to get this error because b!! would be of type Nothing which doesn't define a length property.

I guess it's better to detect that at compile time than having an NPE at runtime.

EDIT: if you extract b!! into a variable, you will actually get an "unreachable code" error, and you can see x here is of type Nothing : 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM