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 is just the normal if/else syntax, so you don't have to remember something else, and (b) it's easy to read.

Also, as you can see from this example, you can use the Scala ternary operator syntax on the right hand side of the equation, as you might be used to doing with Java:

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.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.