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 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
-
Copy
SafeCall.ktfrom thetask10_4subdirectory of your repository to thetask10_5subdirectory. Rename the copy toElvis.kt. -
Modify the code in
SafeCall.ktusing the elvis operator, so that it prints the string???as the result if the user pressesCtrl+Dwhen prompted for input. -
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")