The Scala ternary operator syntax

Scala FAQ: What is the Scala ternary operator syntax?

In other programming languages there is a definite, unique ternary operator syntax, but in Scala, the ternary operator is just the normal Scala if/else syntax:

if (i == 1) x else y

The beauty of this is (a) it’s just the normal if/else syntax, so you don’t have to remember something else, and (b) it’s easy to read.

A typical ternary use

To show a more real-world example, here’s an example of how you can use the Scala ternary operator syntax on the right hand side of the equation:

val a = if (i == 1) x else y

Contrast the readability of the Scala ternary syntax with the Java ternary operator syntax:

i == 1 ? x : y

As you can see, the Scala syntax is much easier to read, especially if you don't normally use the ternary operator syntax very much.