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)
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: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:
So your class representing this response can be:
But… surprise! surprise! Turns out @ben doesn't have a phone in his profile, so the response will be:
For this case you have two options, first is make a default value for your class:
but some parsers will throw an exception. Your second option is… sadly, make it nullable:
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: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.
Yes, It's a simple and understandable example with an analogy. We call it as Safe Navigation in JS.
I think it's clear for everybody now. And thank you for your time :)
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.