Alexey Gravanov

Ternary operator in Scala

Mar 20, 2015

Scala is expressive, requires less ceremony than lots of other languages and enables you to do magic. Of course, there is some black magic as well, but as long as you aware of bad parts of the language, it's fine. Despite that, there are few little things annoying me all the time and one of them is a missing ternary operator. Reasoning about missing ternary operator is that if in Scala, unlike other languages, is actually not a statement, but an expression and you can write things like this:

val a = if (blah) stuff else otherStuff

which makes ternary operator kind of redundant. I completely agree on redundancy, but since I lived in a world where ternary operator exists for a long time, I still think it's nice and more readable than the piece of code above. Actually you can get it by using the following code:

There are two points to understand in the code above:

  • ':' (colon) is not a valid identifier in Scala, but you can use '|' (pipe) instead of it, which looks quite logical as it already has 'or' meaning for other things;
  • arguments have to be passed by name (notice '=>' annotations in function signatures) in order to have lazy evaluation behaviour, like in every other language.

Now you can use it like this:

import TernaryBool._

val blah = true
val x = blah ? "yes" | "no"

Cool, eh? :)

Credits: Original implementation was found on StackOverflow and traced back to Tony's blog.