Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code if object is null?

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?

like image 979
Toni Joe Avatar asked Aug 21 '17 14:08

Toni Joe


People also ask

How do you check if an 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 .

How do you use an if statement with 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 ) ...

Can you call a method on a null object?

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.


1 Answers

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
like image 81
hotkey Avatar answered Oct 02 '22 13:10

hotkey