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:
valabsValue=if(a<0)-aelsea
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)0elsename.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:
defabs(x:Int)=if(x>=0)xelse-xdefmax(a:Int,b:Int)=if(a>b)aelsebvalc=if(a>b)aelseb
See Also
| “Equality, Relational, and Conditional Operators” on the Java Tutorials page |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access