Member-only story
The Elvis Operator in Kotlin
If null, then use this instead
Introduction
“I want to use that value, but if it’s null, then I can use this non-null value instead.”
A lot of times, we are faced with the above situation while we are coding our application. It is probably one of the most common cases to handle in our application code.
Different programming languages offer different ways of doing it, but today, we are going to take a look at how Kotlin does it.
Say hi to the Elvis operator! It is denoted as ?:
.
When to Use the Elvis Operator
The time to use the Elvis operator is when we are expecting a nullable value and need to handle it to avoid the famous NullPointerException
.
Some examples of the use cases include:
- Querying something from a database by primary key which may return no record.
- Mapping from one object to another where one or more of the fields may be null.
How to Use the Elvis Operator
The syntax to use the Elvis operator is pretty simple and straightforward.
val result = x ?: y
This basically says to use x
if the value is not null
, otherwise use y
. The expression on the right-hand side of the Elvis operator or y
in this case, is only evaluated in the case where x
is null
.
y
can be a value, return
an expression or throw
an expression.
Let’s go through a few examples.
Query a Table Which May Return No Record
Below is a function that does GetItem
on a DynamoDB table based on a primary key customerId
and returns the map of its item, if it exists.
Then, we want to get the customer’s email and if it does not exist, we want our application to throw an Exception
.