Kotlin ternary operator

In Kotlin, there is no ternary (or conditional) operator, i.e.if(condition) ? x : y.

So, instead of writing (invalid Kotlin) code like this:

val result: String = coinflip == "heads"
  ? "Flipped to heads"
  : "Flipped to tail";

Kotlin provides if expressions, which provide a very similar structure:

val result: String = if(coinflip == "heads") 
    "Flipped to heads" else 
    "Flipped to tail"

If you’d like to know more about the absence of the ternary operator in Kotlin, please have a look at the discussion on the Kotlin forum.

Leave a Reply

Your email address will not be published. Required fields are marked *