Elvis Operator in Kotlin

Topics Covered

Overview

The Elvis operator in Kotlin acts as a concise tool for handling nullable values. It allows us to provide a default value when a nullable expression is null. Since it acts as a streamlined null-check, it also prevents the need for lengthy conditional structures, thereby enhancing code readability and simplifying error avoidance.

Elvis Operator

The Elvis Operator in Kotlin (null coalescing or null-safety operator) is represented by a question mark and a colon ?:. If it is not null, the operator returns the first expression; if it is, it returns the second expression. By utilizing the Elvis operator in kotlin, we may create easier-to-read and comprehend code that is shorter and more succinct.Even when the conditional expression is null, the Elvis operator in Kotlin ?: is utilized to return the default value, thus verifying that the values are null-safe.

Syntax

Elvis operators in Kotlin come in handy for cases where the variable contains a null reference, so its nullability needs to be checked before utilizing it in the program. However, if the variable is not null, its property is used; otherwise, another default value will be used.

Let's take an example to better understand working for an Elvis operator in kotlin. Say we have a nullable string for which we need to perform a safety check to avoid any errors. There are two ways we can perform this check:

  1. using the if-else expression and,
  2. using the Elvis operator.

Output:

Here ?: is the Elvis operator in Kotlin, which provides a default value in case the expression on the left side (before ?:) is null. If it does come out to be null, -1 as a default value is assigned to the length variable.

Kotlin Elvis Operator in kotlin example

Let's see another example,

Here, the program prompts the user to enter their name. The input is stored in the userName variable, which is a nullable string. We want to provide a default value of "Stranger" in case the user doesn't provide a name (i.e., userName is null).

This uses the Elvis operator in kotlin to include the user's name in the greeting. If userName is not null, it is used in the greeting. If it's null, the default value "Stranger" is used.

Output:

If we do not provide any value it takes the default value as "stranger" Output:

In the above code, we're using the Elvis operator in Kotlin to provide a default value in case the nullable expression is null.For a nullable string str, if it is null, the expression after ?: is evaluated.

Now let's see an example to understand how the Elvis operator in Kotlin uses the throw and return expressions.

Kotlin Elvis Operator in kotlin using throw and return expression

Since Kotlin is intended to be null-safe, handling null values explicitly is required to prevent NullPointerExceptions.

When an expression evaluates to null, a default value is provided using the Elvis operator?:

With the help of the example below, let's put these ideas into practice.

Output:

The variable str is declared as nullable String? in the code, which means it might contain either a valid string or nothing at all. We use the safe call operator ?. in order to access properties or call methods on a nullable variable. For instance,

If str is not null, the expression'str?.length' will return the length of the string str.

If str is null, the entire expression'str?.length' will evaluate to null without raising a NullPointerException.

In the code, you can see the Elvis operator in Kotlin being used in two places:

The Elvis operator in koltin can be used to condense this code into var strLength: Int = str?.length?: -1. If str is empty, the expression str?.length will also be empty, and the Elvis operator in kotlin will then return the value -1 by default.

If test is null in this case, the Elvis operator in kotlin raises an IllegalArgumentException with the message "text exception."The Elvis operator in Kotlin eliminates the need for long null-checking code with if expressions by giving a default value in the case of null values, which results in code that is more concise and easy to understand.

Conclusion

  1. The Elvis Operator in kotlin (null coalescing / null-safety operator) is represented by a question mark and a colon, as in the following ?: If it is not null, the operator returns the first expression; if it is, it returns the second expression.
  2. Kotlin being a null-safe langugae provides a number of mechanisms that can help prevent null references. The Elvis operator among one of them prevents the case of NullPointerException which is thrown when a program attempts to access a null reference.
  3. Kotlin is designed to be null-safe, which means we need to explicitly handle null values to avoid NullPointerExceptions
  4. The Elvis operator provides a default value or behavior in case of null values, without the need for lengthy null-checking code with if expressions.
  5. Even when the conditional expression is null, the Elvis operator ?: is utilized to return the non null value thus verfying that the values are null safe
  6. The Elvis operator eliminates the need for long null-checking code with if expressions by giving a default value in case of null values which results in code that is more concise and easy to understand.