Kotlin Elvis ?: Operator Tutorial

In this section, we will learn what the Elvis operator is and how to use it in Kotlin.

What is Elvis Operator in Kotlin?

The Elvis operator is used to check the value of a nullable variable and see if that variable is pointing to a null value or not.

This operator takes two expressions. The first one is an expression that has a nullable variable and may result in null if the target variable is pointing to a null value. And the second expression is a backup value!

Now if the nullable variable was pointing to an actual object and the first expression could run without a fail (because of null value), then this operator will return the result of this expression.

But if the variable in the first expression was null and the operation failed because of it, then this operator will run the second expression and return the result of that as the final result.

Kotlin Elvis Operator Syntax:

first_expression ?: second_expression

Here the first_expression is the one that contains a variable of nullable type.

The second_expression is the one that will run if the value of the variable in the first expression is set to null.

?: between the first and second expressions we use this symbol.

Example: using the Elvis operator in Kotlin

class Address{
    var city:String = "LA"
    var state:String = "CA" 
}

class Employee{
    var address:Address? = null
    var firstName:String = "John"
    var lastName:String = "Doe"
}
fun main(){

    var emp:Employee? = Employee()
    emp?.address = null 

    var res = emp?.address?.city ?: "There's a null value!"

    println(res)
}

Output:

There’s a null value!

How does Elvis operator work in Kotlin?

So here using the elvis operator we’ve invoked the emp variable to access its address property and get the city property of this inner object. But because the address property is pointing to a null value, then the elvis operator terminated this operation and returned the result of the second expression, which is just a simple string value.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies