for example:
var str: String? = null
str ?: null
When ran returns null, but which one? I don't foresee any practical purpose for this - I'm just curious.
for example:
var str: String? = null
str ?: null
When ran returns null, but which one? I don't foresee any practical purpose for this - I'm just curious.
The elvis operator works like this: If the left operand evaluates to null
, the right operand gets used. See this answer.
In your case, the right null
gets chosen but it's totally useless to use it like this. Using the elvis operator only makes sense if you provide non-null alternatives to the corresponding left operand.
The answer you are looking for is the right hand side value, which is exactly what we would expect. The fact that both of them are null has no bearing on the order in which they are evaluated, Kotlin has a contract and sticks to it.
If I type your code in my editor, I get a warning that "Right operand of elvis operator (?:) is useless if it is null", which seems correct to me. In order to get around that, let's replace the left AND right hand sides with functions that return null instead...
fun alwaysReturnsNull(log: String): String? {
println(log)
return null
}
val str: String? = alwaysReturnsNull("first") ?: alwaysReturnsNull("second")
println(str)
In this case, the output is "first" followed by "second", showing that Kotlin is evaluating these function values in the order you'd expect: left hand of elvis, and then right hand of elvis.