Best way to null check in Kotlin

Kotlin Mobile DevelopmentApps/Applications

In any programming paradigm, it is mandatory to check "null safety" in order to prevent runtime errors. In this article, we will see different ways to check "null safety" in Kotlin.

Example - Using if…else

In most of the programming languages, we have the "if" keyword to check conditions. In Kotlin too, we can use the "if-else" clause to check the null safety of a variable.

fun main() {
   val name="TutorialsPoint.com"
   //null check
   if (name != null) {
      println(name)
   }
   else{
      println("Please enter a value")
   }
}

Output

In the above program, the compiler will check the value of the variable "name". If the value is NULL, then it will print "Please enter a value", otherwise it will print "TutorialsPoint.com".

For the given example, the output will be "TutorialsPoint.com".

TutorialsPoint.com

Example - Using "?.let" operator

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 following example demonstrates how this operator works. This is the best approach when we are using the 'var' variable.

fun main() {
   var name="TutorialsPoint.com"
   // NULL check
   name ?.let{
      println(name)
   }
}

The above expression is equivalent to −

if(name!=null){
   println(name)
}

Output

In this example, let() will execute only when the variable 'name' is not equal to 'null'.

TutorialsPoint.com

Example - Elvis operator

When we have some default value to return in case there is a NULL reference, then it is better to use the Elvis operator. Elvis operator is very common in many programming languages. This is a binary expression that returns the first operand when the expression value is True and it returns the second operand when the expression value is False.

In the following example, we will see how to use this Elvis operator in Kotlin.

fun main(args: Array<String>) {
   val x: String? = null
   val y: String = x ?: "TutorialsPoint.com"
   // it will check whether the value of x is NULL or not.
   // If NULL, then it will return "y", else "x"
   println(x ?: y)
}

Output

TutorialsPoint.com
raja
Updated on 23-Nov-2021 07:27:23

Advertisements