Kotlin Ternary Conditional Operator
What is the equivalent of this expression in Kotlin?
a ? b : c
This is not valid code in Kotlin.
Solution 1:
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.
Solution 2:
TL;DR
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.
Syntactically, there's no need for ternary operator
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.
Solution 3:
You could define your own Boolean
extension function that returns null
when the Boolean
is false
to provide a structure similar to the ternary operator:
infix fun <T> Boolean.then(param: T): T? = if (this) param else null
This would make an a ? b : c
expression translate to a then b ?: c
, like so:
println(condition then "yes" ?: "no")
Update: But to do some more Java-like conditional switch you will need something like that
infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null
println(condition then { "yes" } ?: "no")
pay attention on the lambda. its content calculation should be postponed until we make sure condition
is true
This one looks clumsy, that is why there is high demanded request exist to port Java ternary operator into Kotlin