Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: coding discussion: elegant way to check multiple variables which could null

Tags:

null

kotlin

I use Kotlin to Programm Android Apps. For null-pointer safety one needs to check if all references are non-null. However if only one is null then we should inform the user that something went wrong.

It is important for me to program in a concise readable manner.

I am looking for a short and easy understandable solution.

The standard way would be:

if  (b != null && a != null && c !=null ...) println ("everything ok.")
else println("Something went wrong")
like image 968
Marcel Sonderegger Avatar asked Oct 07 '18 14:10

Marcel Sonderegger


People also ask

How do I check if a variable is null in Kotlin?

You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.

Which operators are used for checking null in conditions in Kotlin?

The Elvis operator is used to return a non-null value or a default value when the original variable is null. In other words, if left expression is not null then elvis operator returns it, otherwise it returns the right expression. The right-hand side expression is evaluated only if the left-hand side found to be null.

How do you ensure null safety in Kotlin?

Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.

Can any be null Kotlin?

Consequently, any variable cannot contain the null value unless you explicitly say it can. This way, you can avoid the danger of null references, and you do not have to wait for exceptions or errors to be thrown at runtime. Kotlin supports this possibility since its first release, and it is called null safety.


1 Answers

Here are two concise ways to write the condition:

listOf(a, b, c).any { it == null }

listOf(a, b, c).filterNotNull().any()

In context, this is how you can use it:

println(if (listOf(a, b).any { it == null })) "Something went wrong"
        else "Everything ok.")
like image 168
Marko Topolnik Avatar answered Dec 31 '22 19:12

Marko Topolnik