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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.