Comparison and Logic
The club awards a badge for a week with at least three runs and more than 20 km. That rule is two comparisons joined by "and". Scala's comparison and logical operators are short to write, but two of their behaviours surprise people who come from Java.
The rule
==compares values;&&and||stop as soon as the answer is known.
Comparison operators produce a Boolean:
| Operator | Meaning |
|---|---|
== |
equal |
!= |
not equal |
< and > |
less than, greater than |
<= and >= |
at most, at least |
== compares values. Two strings with the same characters are equal, and so are two lists with the same elements, even when they are separate objects:
"Asha" == "As" + "ha" // true
List(5.0, 8.5) == List(5.0, 8.5) // trueJava's == asks whether two references point to the same object. In Scala that job belongs to eq, which you will rarely need.
Scala 3 also refuses to compare values that could never be equal: 8 == "8" is a compile error, not a quiet false.
Logical operators combine Booleans: && means and, || means or, and ! means not.
val runs = List(5.0, 8.5, 3.2, 10.0)
val badge = runs.length >= 3 && runs.sum > 20 // true&& and || short-circuit: the right side runs only if the left side has not already decided the answer. With &&, a false on the left means the right is skipped. That makes guards like this safe:
runs.nonEmpty && runs.head > 5On an empty list, runs.nonEmpty is false, so runs.head, which would throw, never runs.
One more surprise: decimals are approximate, so 0.1 + 0.2 == 0.3 is false. Compare decimals with a tolerance instead, as in math.abs(a - b) < 1e-9.
The shortcut
Read && as "stop at the first false" and || as "stop at the first true". Put the cheap or protective test on the left, and the test that could fail or throw on the right.
The expression
runs.nonEmpty && runs.head > 5, whererunsis an empty list.
Drills
Answer fast — trust the rule.
What is "Asha" == "As" + "ha" in Scala?
What does Scala 3 do with 8 == "8"?
runs is an empty list. What is runs.nonEmpty && runs.head > 5?
What is 0.1 + 0.2 == 0.3?
With km = 8.5, what is !(km > 10) && km > 3?
Remember
==compares values such as strings and lists;eqchecks identity, and Scala 3 rejects comparing unrelated types.&&stops at the first false and||at the first true, so put the protective test on the left.- Trap: comparing decimals with
==; use a tolerance.
