How to use a Scala if/then statement like a ternary operator

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.6, “How to use a Scala if/then statement like a ternary operator.”

Problem

You’d like to use a Scala if expression like a ternary operator to solve a problem in a concise, expressive way.

Solution

This is a bit of a trick question, because unlike Java, in Scala there is no special ternary operator; just use an if/else expression:

val absValue = if (a < 0) -a else a

Because a Scala if expression returns a value, you can embed it into a print statement:

println(if (i == 0) "a" else "b")

You can use it in another expression, such as this portion of a hashCode method:

hash = hash * prime + (if (name == null) 0 else name.hashCode)

Discussion

The Java documentation page shown in the See Also section states that the Java conditional operator ?: “is known as the ternary operator because it uses three operands.” Unlike some other languages, Scala doesn’t have a special operator for this use case.

In addition to the examples shown, the combination of (a) if statements returning a result, and (b) Scala’s syntax for defining methods makes for concise code:

def abs(x: Int) = if (x >= 0) x else -x
def max(a: Int, b: Int) = if (a > b) a else b
val c = if (a > b) a else b

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

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.