How to run code if object is null?

Solution 1:

You can use the elvis operator and evaluate another block of code with run { ... }:

data?.let {
    // execute this block if not null
} ?: run {
    // execute this block if null
}

But this seems not to be quite as readable as a simple if-else statement.

Also, you might find this Q&A useful:

  • In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

Solution 2:

Here's a concise syntax using the Elvis operator. Recall the Elvis operator only executes the right side if the left side evaluates to null.

data ?: doSomething()

Solution 3:

You can create an infix function like this:

infix fun Any?.ifNull(block: () -> Unit) { 
  if (this == null) block()
}

Then you can do this:

data ifNull {
  // Do something
}

Solution 4:

Just use a normal if:

if (data == null) {
  // Do something
}