Better Programming

Advice for programmers.

Follow publication

Member-only story

The Elvis Operator in Kotlin

billydharmawan
Better Programming
Published in
3 min readFeb 22, 2020

Photo by Shane Hauser on Unsplash

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

billydharmawan
billydharmawan

Written by billydharmawan

An ordinary man trying to leave a good legacy on earth

Responses (2)

Write a response

Also, a fun fact about the operator that I read in a book. It is named after Elvis presley cuz it looks like his hairstyle 😄😄

--

Why this needed an entire article is beyond me.

--