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