Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Elvis Operator

Basic Concept

A common requirement is to evaluate an expression and, if the result is null, substitute a non-null ‘default value’ in its place. This can, of course, be done using an explicit null check:

val result = when (text) {
    null -> "☹️"
    else -> text.reversed().uppercase()
}

But Kotlin provides another simplifying tool for this, the elvis operator, ?:

Note: the technical term for this is the ‘null coalescing operator’, but pretty much everyone calls it the elvis operator, because it looks like Elvis Presley when rotated clockwise!

The elvis operator is so named because, when rotated clockwise, it looks like Elvis Presley...

The example above can be written much more concisely using a combination of the safe call and elvis operators:

val result = text?.reversed()?.uppercase() ?: "☹️"

The value of result will be determined by the expression to the left of elvis if that expression evaluates to anything other than null; otherwise, it will be determined by evaluating the expression to right of elvis.

Task 10.5

  1. Copy SafeCall.kt from the task10_4 subdirectory of your repository to the task10_5 subdirectory. Rename the copy to Elvis.kt.

  2. Modify the code in SafeCall.kt using the elvis operator, so that it prints the string ??? as the result if the user presses Ctrl+D when prompted for input.

  3. Compile and run the program to verify that it behaves correctly.

Other Examples

When we looked at maps, we saw that you can access stored values using getOrElse(). This returns the value associated with the given key if that key is present, or else the result of executing the given lambda expression if it is not.

prices.getOrElse(item) { 15 }

prices.getOrElse(item) {
    throw NoSuchElementException("No price for $item")
}

You can achieve the same results more concisely, using [] and the elvis operator:

prices[item] ?: 15

prices[item] ?: throw NoSuchElementException("No price for $item")