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?
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
Use the ISNULL function with the IF statement when you want to test whether the value of a variable is the null value. This is the only way to test for the null value since null cannot be equal to any value, including itself. The syntax is: IF ISNULL ( expression ) ...
You can call a static method on a null pointer. The pointer will naturally be completely ignored in a static method call, but it's still a case when something that (without looking at the class definition) seemingly should cause a NullPointerException runs just fine.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With