Search code examples
kotlinnullable

Assignment after not null check


I expected that the type of a variable is promoted to a non-null type after a not-null check (like in the Dart language).

val someMap = mapOf("a" to 0L)
val a = someMap['a'] // a is of type Long?
if (a != null) {
    val b = a // b is of type Long? and not of type Long. Why? 
}

Can someone explain why this is not the case? Just a matter of taste of the language designers?


Solution

  • Since there is smart-casting, it doesn't matter. It will allow you to use members of a or b inside the if statement without null-safe calls (?.) or null assertions (!!). You can also safely declare b to be a Long without the compiler complaining:

    if (a != null) {
        val b: Long = a
    }
    

    It is I think a design choice for how implicit types should be inferred that b's type must be explicitly declared if you want it to be considered non-nullable. This is only relevant if passing it to a function with generics, since there is smart-casting.