Null safety while casting


#1

Hi everyone,

I noticed that nullability is not checked by compiler when casting class to subclass.
Take a look at this example:

open class A {
fun getInfo() = “A”
}

class B : A()

fun getA() :A? {
return null
}

private fun test() {
val b = getA() as B
println(b.getInfo())
}

As you can see, function getA() can return null value but compiler allows to cast result of this function to non-nullable subtype B. But in runtime, if getA() returns null we get an exception: “null cannot be cast to non-null type B”

Is this a bug / missing feature or is there some reason why compiler can not or should not do this check at compile time and allow only cast to B? (nullable version of B) ?

I am using Kotlin 1.1.4


#2

No, this is not a bug. You can always try to cast (the compiler will warn you if it can determine that the cast can never succeed), but an exception will be thrown at run time if the object being cast is not of the correct type. If you never want an exception you should use as?, but then the type of b changes to B?.