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.”
You’d like to use a Scala if expression like a ternary operator to solve a problem in a concise, expressive way.
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
hash = hash * prime + (if (name == null) 0 else name.hashCode)
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
- “Equality, Relational, and Conditional Operators” on the Java Tutorials page
- Many years ago I shared some Java ternary operator examples