3.6. Using the if Construct 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 problem, 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 an 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 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

“Equality, Relational, and Conditional Operators” on the Java Tutorials page

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.