Home > database >  Assignment after not null check
Assignment after not null check

Time:12-09

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?

CodePudding user response:

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.

CodePudding user response:

It is called smart casting, basically Kotlin is smart enough to determine that variable can no longer be null after check. More detail and can be found here if you are interested

CodePudding user response:

As to why, only the creators of kotlin can know. But what you can do is this if you want a Long instead of Long? there is this

val b = a!!

CodePudding user response:

What you can do instead of explicit null check is using let{} as follows:

val someMap = mapOf('a' to 0L)
val a = someMap['a'] // a is of type Long?
a?.let {
    val b = it // b is of type Long
}
  • Related