Best way to null check in Kotlin?

pdeva picture pdeva · May 14, 2016 · Viewed 75.5k times · Source

Should I use double =, or triple =?

if(a === null)  {
//do something
}

or

if(a == null)  {
//do something
}

Similarly for 'not equals':

if(a !== null)  {
//do something
}

or

if(a != null)  {
//do something
}

Answer

Benito Bertoli picture Benito Bertoli · May 14, 2016

A structural equality a == b is translated to

a?.equals(b) ?: (b === null)

Therefore when comparing to null, the structural equality a == null is translated to a referential equality a === null.

According to the docs, there is no point in optimizing your code, so you can use a == null and a != null


Note that if the variable is a mutable property, you won't be able to smart cast it to its non-nullable type inside the if statement (because the value might have been modified by another thread) and you'd have to use the safe call operator with let instead.

Safe call operator ?.

a?.let {
   // not null do something
   println(it)
   println("not null")
}


You can use it in combination with the Elvis operator.

Elvis operator ?: (I'm guessing because the interrogation mark looks like Elvis' hair)

a ?: println("null")

And if you want to run a block of code

a ?: run {
    println("null")
    println("The King has left the building")
}

Combining the two

a?.let {
   println("not null")
   println("Wop-bop-a-loom-a-boom-bam-boom")
} ?: run {
    println("null")
    println("When things go null, don't go with them")
}