NullPointerException from safe type!


#1

This code compiles but, when I run it I get NullPointerException and I don’t know why. Is it bug in Kotlin? Or is it my environment?

class Node {
    init { log() }
    val label:String = "hello"
    fun log() { println(label.length) }
}
fun main(args:Array<String>) {
    Node()
}

#2

#3

This happens because the label property is not initialized by the time log() is called. Try to swap init block & label declaration.


#4

This looks to me as a bug in the compiler. The complier should flag this as a compilation error.

Rearranging blocks is just a workaround.

@mustafa01991: please report this as a bug and let’s see what the Kotlin team thinks.