is there any ternary operator in kotlin ?
# android
a
is there any ternary operator in kotlin ?
🚫 11
l
if
is an expression. You can do
val a = if (condition) "something" else "something else"
. See https://kotlinlang.org/docs/reference/control-flow.html
👍 1
c
if
statements are expressions in Kotlin (they return a result) and so can be used to do exactly the same thing as the ternary operator, but is less confusing.
Copy code
a = b ? c : d
is the same as
Copy code
a = if(b) c else d
d
6 extra bytes though ... P:))
s
The elvis operator
?:
works well as a shorthand ternary dealing with nulls.
Copy code
a = nullableValue ?: nonnullDefaultValue
a
thanks