1. Introduction

One of the common bugs in many programming languages is accessing null references, which results in throwing a NullPointerException. The are several mechanisms that can help to avoid null references in Kotlin. One of them is the Elvis operator. In this short tutorial, we’ll take a look at how this operator works.

2. What Is the Elvis Operator?

A question mark followed by a colon represents the Elvis Operator, like this ?:. The name comes from the fact that the operator, seen from the side, resembles an Elvis Presley emoticon with his characteristic hairstyle. Another name for the Elvis operator is the null coalescing operator or null-safety operator. The operator returns the first expression if it is not null, or it returns the second expression otherwise. By using the Elvis operator, we can write shorter and more concise code that is easier to read and understand.

3. Syntax

First, let’s take a peek at the sample of code without the Elvis operator:

var word: String? = "Elvis"
val length: Int = if (word != null) word.length else -1
assertEquals(5, length)

The syntax for using the Elvis operator is fairly straightforward. Instead of writing complete if expression, we can write this with the Elvis operator?: Let’s take a look at the example:

val word: String? = "Elvis"
val length: Int = word?.length ?: -1
assertEquals(5, length)

If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise, it returns the expression to the right. In this case, the actual length of the word is not null, so the operator returns 5.

Let’s assign a null value to our variable and check what operator returns:

val word: String? = null
val length: Int = word?.length ?: -1
assertEquals(-1, length)

In this case, it returns -1.

Moreover, we can also use throw and return on the right part of the Elvis operator. Those keywords are expressions in Kotlin. For instance:

val word: String? = null
val exception = assertThrows(IllegalArgumentException::class.java) {
    word?.length ?: throw IllegalArgumentException("empty string not allowed")
}
assertEquals("empty string not allowed", exception.message)

Next, let’s check more complex examples with chain Elvis operators:

val a = null
val b = null
val result = a ?: b ?: "a and b are null"
assertEquals("a and b are null", result)

In the case above, both values have a null reference, so it returns the right side of the second Elvis operator.

4. Conclusion

In this article, we’ve seen the Elvis operator in practice. This operator is really easy to use and handles situations where we expect a null value in a pretty clean way. As usual, all the examples are available over on GitHub.

Comments are closed on this article!