Why doesn't Kotlin support "ternary operator"

Viewed 2724

Explain: This question is more about the design intentions of Kotlin. Many expression languages support both Ternary operator and if expression [e.g., Ruby, Groovy.]


First of all, I know Groovy supports both Ternary operator and Elvis operator: Ternary operator in Groovy. So I don't think it's a syntax problem.


Then the official documents said:

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

And this doesn't convince me. Because Kotlin support Elvis operator which ordinary if works just fine in that role either.

I think ternary operator is sometimes better than ordinary if, though I wonder why doesn't Kotlin just support ternary operator?

5 Answers

Programmers at some point, have to make a decision to execute a block of code, this is known as Control Flow. If statement is most basic way to control flow in Kotlin. Important point to note that in Kotlin, If is an expression not a statement as it is Java.

  1. Statement: A statement is an executed line which does not return a value. As a result, statement cannot sit right side of an equal sign.
  2. Expression: An expression returns a value.So the result of a Kolin If expression can be assigned to a variable.

    Because of this the ternary expression would be redundant and does not exists in Kotlin. In Java we would write (Here is the answer of your question)

For Example

Ternary Operator in Java

int lowest = (a < b) ? a : b;

In Kotlin we can write something similar using the if expression.

val lowest = if(a < b) a else b

NOTE: When If is used as an expression it must contain an else clause. The expression must have a value in all case.

Because if-else is an expression in Kotlin :

String check = number % 2 == 0 ? "even" : "odd" // Java

if (number % 2 == 0) "even else "odd" // Kotlin

So that's why there are no ternary operator in Kotlin, Moreover you can use when expressions too, it's so handy if you want to provide a lot of possible execution paths

Related