The Elvis Operator in Kotlin: Behind the Scenes!

Estefania Cassingena Navone
Techmacademy
Published in
3 min readAug 12, 2018

πŸ’₯ Elvis?!

The first time I read about the Elvis operator I was really amazed to find that Elvis Presley had been included in the world of Computer Science. πŸ‘

Let’s learn more about it and how it’s use in Kotlin!

πŸ‘‹ Meet the Elvis Operator

Elvis Operator

Yes! This is the Elvis Presley emoticon, the reason for the name! Let me show you how it works:

Null Safety

When we define a variable, we can use this syntax:

var <variable_name> = <first_operand> ?: <second_operand>
  • Notice the Elvis Operator to the right. It operates on two operands and returns the first operand if the value is not null, else it returns the second operand.

πŸ’‘ Importance: This gives us a way to provide a default value for the variable in case the first operand is null.

This is very useful when we are working with a variable that is nullable.

For Example:

var customerName : String? = nullvar nameLength = customerName?.length ?: -1 // Notice the Operator

πŸ’‘ Note: Notice that we need to add a question mark ? after the name of the variable. This is called a Safe Call that returns the length of the string if customerName is not null, else if customerName is null, it returns null. I will write an article on this topic as part of the Kotlin Series (Stay tuned! πŸ‘).

⚠️ Throwing Exceptions

The Elvis Operator can also be used to validate function parameters and throw exceptions if necessary. Let me illustrate this:

Let’s say we defined a method getAge() for a Pet class and then we call a function that takes in an instance of a Pet :

Example of Throwing Exceptions with the Elvis Operator

Take a look at this line in more detail:

Close Up

If the getAge() method returns null, an exception is thrown because the age property is required.

This way we can write much cleaner code thanks to the wonderful syntax and features Kotlin offers. πŸ‘ πŸŽ†

πŸ“š To Learn More about the Elvis Operator and Kotlin…

πŸ‘‹ Now…

I would like to personally invite you to follow Techmacademy to find articles specially written for awesome learners like you.

If you found this article helpful, your claps are very much appreciated to help others who are embarking on this journey.

I would love to read your comments and thoughts.

Follow me on Medium πŸ˜ƒ πŸ‘

--

--

Estefania Cassingena Navone
Techmacademy

Udemy Instructor | Developer | MITx 6.00.1x Community TA | Writer @Medium | CS & Mathematics Student | WTM Udacity Scholar