Learn/Scala/4. Making decisions
Lesson 4 of 8
Sign in

Scala, lesson 4

Making decisions

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.

if, then, else

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.

if is an expression

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.

Exercise 1

What's the weather like?

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

produces a value
var

Both branches should give the same type, and you need the else, otherwise there is no value for the "false" case.

Comparison operators

OperatorMeaning
==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.

Combining conditions

OperatorMeaningExample
&&and: both must be trueage >= 13 && age <= 19
||or: at least one must be trueday == "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.

match

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:

Further reading

  • Scala 3 Book: Control Structures
  • Scala 3 Book: A Taste of Scala, control structures

Read a whole-number temperature in Celsius and print one word describing it:

  • below 0: freezing
  • 0 to 15: cold
  • 16 to 25: mild
  • above 25: hot

Sample 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"
18
mild
2024
2024 is a leap year