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")
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.
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.
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.
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.
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.")
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