How to run code if object is null?

Toni Joe picture Toni Joe · Aug 21, 2017 · Viewed 28.1k times · Source

In Kotlin, I can run code if an object is not null like this:

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

but how can I execute a block of code if the object is null?

Answer

hotkey picture hotkey · Aug 21, 2017

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: