DEV Community

Anastasia
Anastasia

Posted on

Elvis operator ?:

I have started to learn Kotlin. And my lector told me about Elvis operator, but for me, it's a ternary operator. Oh... I didn't know about that, especially why people have kind of this association in their mind.

Do you know about that? Or have you faced such a situation?

Top comments (4)

Collapse
 
sierisimo profile image
Sinuhe Jaime Valencia

I like the explanation from @neilonsoftware but I like to give examples.


Oh the ternary controversy…

In Kotlin is possible to use the if statement as an expression:

val x = if(condition) value else default

So the developers and community behind the language decided to stay with this instead of a ternary.

Now, for the Elvis Operator, it works over nullable values and the main intention is to remove the null from the equation as soon as you found one:

val x = myInstance?.someFoo ?: defaultFoo

This way you can just assign or use a default value as soon as something is missing. One example is for a response from a web service.

Let's say you call a service that gives you a JSON with the information from a person:

{
  "first_name": "Sinuhe",
  "last_name": "Jaime",
  "phone": "12345-54321"
}

So your class representing this response can be:

data class Person(
  val firstName: String,
  val lastName: String,
  val phone: String
)

But… surprise! surprise! Turns out @ben doesn't have a phone in his profile, so the response will be:

{
  "first_name": "Ben",
  "last_name": "Halpern"
}

For this case you have two options, first is make a default value for your class:

data class Person(
  
  val phone: String = ""
)

but some parsers will throw an exception. Your second option is… sadly, make it nullable:

data class Person(
  
  val phone: String?
)

in that way, if your parser doesn't have an strategy for missing fields, you can simply assign or keep the value as null, then you have a reason for the elvis operator, when using a Person in a function you can simply:

fun operateOverDataFromPerson(person: Person){
  
  val phone = person.phone ?: "-"
}

And nothing will break.

Collapse
 
miledi_delafer profile image
Anastasia

Thanks, it's a quite detailed example. I agree that we need to take care of missing fields. It's a very popular case.

 
miledi_delafer profile image
Anastasia

Yes, It's a simple and understandable example with an analogy. We call it as Safe Navigation in JS.

Ok

I think it's clear for everybody now. And thank you for your time :)

Collapse
 
miledi_delafer profile image
Anastasia

Thank you very much for your explanation, it's good to know it. Because I often use the ternary operator in js. And I thought it's pretty the same.