Arithmetic Operators
The logbook shows pace as minutes and seconds per kilometre, like 5:06, not as 306 seconds. Turning one into the other takes three arithmetic operators and a clear idea of what each one keeps.
The rule
/keeps the whole part,%keeps the leftover; the wider type wins.
Scala's arithmetic operators are the familiar ones:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
add | 5.0 + 8.5 |
13.5 |
- |
subtract | 10 - 3 |
7 |
* |
multiply | 12 * 400 |
4800 |
/ |
divide | 306 / 60 |
5 |
% |
remainder | 306 % 60 |
6 |
- With two whole numbers,
/gives the whole part and throws away the rest, and%gives exactly what/threw away.306 / 60is 5 and306 % 60is 6, because 5 × 60 + 6 = 306. - If either side is a
Double, the result is aDouble:306 / 60.0is5.1. - The sign of
%follows the left side:-7 % 3is-1. - Whole-number division by zero throws an
ArithmeticException. Decimal division by zero does not:10.0 / 0isInfinity.
A var can be updated in place with +=, -=, *=, /= and %=:
var weekKm = 0.0
weekKm += 5.0 // same as weekKm = weekKm + 5.0
weekKm += 8.5 // now 13.5There is no ++ or -- in Scala. laps++ is a compile error; write laps += 1.
The + operator also joins strings: "Asha" + " ran" is "Asha ran".
The shortcut
For anything counted in groups of a fixed size, such as 60 seconds to a minute, use the pair trick: total / size gives the big units and total % size gives the leftover small units. Check with big × size + leftover = total.
Seconds per kilometre
Both are whole numbers:
1530 / 5is 306 seconds for each kilometre.
The trap: letting a Double into the pair trick. 306.0 / 60 is 5.1, which means 5.1 minutes, not 5 minutes and 10 seconds.
Drills
Answer fast — trust the rule.
What is 1530 / 60?
What is 1530 % 60?
What is -7 % 3 in Scala?
Given var laps = 12, how do you add one lap?
What do 10 / 0 and 10.0 / 0 do?
Remember
/keeps the whole part of a whole-number division and%keeps the leftover; any Double makes the result a Double.- Pair trick:
total / sizeandtotal % size, checked by big × size + leftover. - Trap: Scala has no
++, and a Double in the pair trick gives decimal minutes.
