What is the equivalent of this expression in Kotlin?
a ? b : c
This is not valid code in Kotlin.
Briefly speaking, there is no ternary operator in Kotlin.
There is no ternary operator in kotlin, as the if else block returns the value.
In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator ( condition ? then : else ) because ordinary if works fine in this role. If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.
== operator in Kotlin only compares the data or variables, whereas in Java or other languages == is generally used to compare the references. The negated counterpart of == in Kotlin is != which is used to compare if both the values are not equal to each other.
In Kotlin, if
statements are expressions. So the following code is equivalent:
if (a) b else c
The distinction between expression and statement is important here. In Java/C#/JavaScript, if
forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.
// Valid Kotlin, but invalid Java/C#/JavaScript var v = if (a) b else c
If you're coming from a language where if
is a statement, this might seem unnatural but that feeling should soon subside.
if (a) b else c
^ is what you can use instead of the ternary operator expression a ? b : c
which Kotlin syntax does not allow.
In Kotlin, many control statements, such as if
, when
, and even try
, can be used as expressions. As a result, these statements can have a result which may be assigned to a variable, be returned from a function, etc.
As a result of Kotlin's expressions, the language does not really need the ternary operator.
if (a) b else c
is what you can use instead of the ternary operator expression a ? b : c
.
I think the idea is that the former expression is more readable since everybody knows what ifelse
does, whereas ? :
is rather unclear if you're not familiar with the syntax already.
Nevertheless, I have to admit that I often miss the more convenient ternary operator.
Other Alternatives
when
You might also see when
constructs used in Kotlin when conditions are checked. It's also a way to express if-else cascades in an alternative way. The following corresponds to the OTs example.
when(a) { true -> b false -> c }
Extensions
As many good examples (Kotlin Ternary Conditional Operator) in the other answers show, extensions can also help with solving your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With