Switch case
One value, some cases, a default — and what it works on.
A chain of if/else if quickly becomes unreadable when the same value is tested against ten
possibilities. switch replaces it.
@entry(start)
object MyProgram {
start() {
var day := 2;
switch (day) {
case 1:
Console.print(text: "Monday");
break;
case 2:
Console.print(text: "Tuesday");
break;
default:
Console.print(text: "some other day");
}
}
}
One value, some cases, a way out
switch (day) evaluates the value once, then looks for the case that matches it. Found, it
runs what follows. None matches, it takes the default.
The break closes the case: it makes sure the cases below it are not run.
The default is not compulsory, but leaving it out has a consequence: a value no case foresees
then does nothing at all, silently. Writing it, if only to flag the unexpected, costs two
lines.
What it works on
Integers and texts, nothing else. A switch on a text compares contents, like the = of
section 3:
switch (name) {
case "simon":
Console.print(text: "known");
break;
default:
Console.print(text: "unknown");
}
There is no switch on an object. Branching on one is written with if.
Your turn
- Give
daya value nocaseforesees: thedefaultanswers. - Remove the
breakfromcase 1:and setdayto 1: two lines appear. - Remove the
defaultand give an unforeseen value: the program prints nothing, and does not complain. That is exactly the silence adefaultavoids. - Rewrite the same choice as
if/else ifand compare the two as reading.