The Elvis Operator in Kotlin: Behind the Scenes!
π₯ 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
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
:
Take a look at this line in more detail:
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β¦
- Kotlin Documentation β Elvis Operator.
- Elvis Operator β Wikipedia.
- Kotlin 101: val vs var Behind the Scenes!
π 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 π π