https://kotlinlang.org logo
#android
Title
# android
a

Akbar

09/04/2019, 2:48 PM
is there any ternary operator in kotlin ?
🚫 11
l

Luke

09/04/2019, 2:56 PM
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

Casey Brooks

09/04/2019, 2:57 PM
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

DALDEI

09/04/2019, 3:34 PM
6 extra bytes though ... P:))
s

Sam

09/04/2019, 4:50 PM
The elvis operator
?:
works well as a shorthand ternary dealing with nulls.
Copy code
a = nullableValue ?: nonnullDefaultValue
a

Akbar

09/05/2019, 6:45 AM
thanks
5 Views