I would like to simplify this:
var countA: Int = 0
var countB: Int = 0
if (validItem) {
if (region.equalsIgnoreCase( "US" )) {
if (itemList > 0) {
countB = 1
} else {
countA = 1
}
} else {
countB = 1
}
} else {
countA = 1
}
How do I use ternary operator in scala.
I think the short answer is that in Scala there is no
?:
ternary operator. Although you can imitate the syntax using implicits (see @jwvh's answer), I think it doesn't really simplify anything.There are a couple of important properties of the conventional
?:
following from the previous property, the ternary operator always returns a value (this is mostly the point of using
?:
)branches are evaluated lazily
As you see, in Scala
if-else
(withelse
) construction satisfies these properties. This is not the case forif-else
construction in some other languages, like C or Java, because it doesn't return a value.So the bottom line is that in
Scala
you don't need a ternary operator, because you can just useif-else
.UPDATE
As Alexey Romanov mentions in the comments,
if
statement withoutelse
actually satisfies the first condition as well. When you writeit actually means
if (true) 1 else ()
, soresult
will have typeAnyVal
instead ofInt
, because the return type of theif
expression is the lowest common bound of the both branches (Int
andUnit
in this case).This might be a bit confusing for a "newbie", but you could attach a ternary method to the
Boolean
class like so.Usage:
To expand on @0__'s answer (if that is his/her real name), you can also use tuples to assign to two variables at once.
You should not need to use a ternary operator in Scala. In Scala,
if
is an expression not a statement, you can sayval x = if (b) 1 else 2
.The usage of
var
in your example also points to a problem, because you can usually avoid this when you use theif
as an expression.Let's try to break down the code to avoid the
var
, i.e. first remove allif
statements that are not expressions with a correspondingelse
and always provide both values:Now we can define the condition for which either of
countA
andcountB
is one:and then: