data classPerson(valfirstName:String,vallastName:String,valphone: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 classPerson(…valphone:String="")
but some parsers will throw an exception. Your second option is… sadly, make it nullable:
data classPerson(…valphone: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:
Hi everyone, I'm a full stack web developer. I always try to improve myself and learn something new for me, be passionate about what I am doing, & travel around the world.
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.