How to run code if object is null?
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
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()
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
}