Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin null checks(!!) when nullability is already checked

Tags:

android

kotlin

I have a question about Kotlin and its null checks warnings.

Let's assume I created an object called "user" with some attribute like name, surname, etc etc. The following code is an example:

if(user != null) {
    val name = user!!.name
    val surname = user.surname
    val phoneNumber = user.phoneNumber
} else 
    // Something else

Why, even if I checked that user is not null, Kotlin wants me to use !! the first time I call user? It cannot be null at this point.

I know that I can use the following block but I don't understand this behavior.

user?.let{
    // Block when user is not null
}?:run{
    // Block when user is null
}
like image 580
Lorenzo Vincenzi Avatar asked Jun 08 '26 06:06

Lorenzo Vincenzi


1 Answers

There's a reason for that behavior. Basically, it's because the compiler can't ensure that the value of user doesn't become null after the if check.

This behavior is only applicable for var user, not for val user. So for example,

val user: User? = null;
if (user != null) {
  // user not null
  val name = user.name // won't show any errors
}
var user: User? = null;
if (user != null) {
  // user might be null
  // Since the value can be changed at any point inside the if block (or from another thread).
  val name = user.name // will show an error
}

let allows you to ensure immutability even for var variables. let creates a new final value separate from the original variable.

var user: User? = null
user?.let {
  //it == final non null user
  //If you try to access 'user' directly here, it will show error message,
  //since only 'it' is assured to be non null, 'user' is still volatile.
  val name = it.name // won't show any errors
  val surname = user.surname // will show an error
}
like image 189
Chrisvin Jem Avatar answered Jun 10 '26 13:06

Chrisvin Jem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!