In languages that have a ternary operator , you use it like this
String value = condition ? foo : bar;
In Kotlin, you can do the same using if and else
var value = if(condition) foo else bar;
Its a bit verbose than a ternary operator . But the designers of Kotlin thought that everything was in order. You can use if-else like this because in Kotlin if there is an expression and returns a value
Elvis operator is essentially a compressed version of the ternary conditional operator and is equivalent to the following in Kotlin.
var value = if(foo != null) foo else bar;
But if the Elvis operator , it is simplified as follows:
var value = foo ?: bar;
This is a significant simplification, and Kotlin decided to keep it.
dishan
source share