re: Elvis operator ?: VIEW POST


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 = ?: "-"

And nothing will break.


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

code of conduct - report abuse