![]() |
VOOZH | about |
In Kotlin, the Elvis Operator (?:) is a very useful tool when working with nullable variables. It helps us to provide a default value if an expression returns null. This operator makes our code shorter, cleaner, and safer when dealing with possible null values.
Sometimes in Kotlin, we declare variables that can hold null references. Before using such variables, we usually check if they are null or not to avoid errors like NullPointerException. Instead of using long if-else conditions, we can use the Elvis Operator (?:) to make the code much simpler.
val result = expression ?: default_valueIf expression is not null, it returns the value of the expression. If expression is null, it returns the default_value after ?:.
To normally handle null values using an if-else block we do it the following way as shown below.
Example:
Output:
Length of st is -1
Length of st1 is 15
Example:
In this example, for "st", since it is null, we return -1 and for "st1", since it is not null, we return its length (15).
We can do the same thing more easily using the Elvis Operator (?:) as shown below.
Example:
Output:
Length of st is -1
Length of st1 is 15
Explanation: