Scala, lesson 4
So far every program has run every line. Real programs need to choose: charge shipping only
on small orders, warn when a battery is low. In Scala you make that choice with if.
Scala 3 writes the condition after if and before then. No parentheses are needed:
The indented lines under then run when the condition is true; the lines under else run
otherwise. The else part is optional. For more than two cases, chain with else if:
Scala checks the conditions from top to bottom and runs only the first branch that matches.
In Scala, if doesn't just run code; it . That means you can assign its
result directly, which often removes the need for a :
2 exercises to try what you just read.
varBoth branches should give the same type, and you need the else, otherwise there is no value
for the "false" case.
| Operator | Meaning |
|---|---|
== | equal |
!= | not equal |
< <= | less than, less or equal |
> >= | greater than, greater or equal |
Each comparison gives a Boolean. In Scala, == compares values, so it works the way
you expect on strings too: "tea" == "tea" is true.
| Operator | Meaning | Example |
|---|---|---|
&& | and: both must be true | age >= 13 && age <= 19 |
|| | or: at least one must be true | day == "Sat" || day == "Sun" |
! | not: flips true and false | !isOpen |
&& and || short-circuit: if the left side already decides the answer, the right side
is never evaluated. So count != 0 && total / count > 5 never divides by zero.
When you compare one value against several possibilities, match is often clearer than a
chain of ifs. Each case is a pattern; _ matches anything, and a guard (if ...) adds an
extra condition. Like if, match is an expression:
Read a whole-number temperature in Celsius and print one word describing it:
freezingcoldmildhotSample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap
years only if they are also divisible by 400. Read a year and print either
<year> is a leap year or <year> is not a leap year.
Sample input:
Sample output:
val battery = 12
if battery < 20 then
println("Low battery!")
println("Plug in soon.")
else
println("Battery OK")if score >= 90 then println("A")
else if score >= 80 then println("B")
else println("C or below")val fee = if total >= 50 then 0 else 5
val label = if isMember then "member" else "guest"val dayType = day match
case "Sat" | "Sun" => "weekend"
case _ => "weekday"
val size = n match
case 0 => "none"
case x if x < 10 => "a few"
case _ => "lots"18mild20242024 is a leap year