Control Flow
Choice Labels
Choose a label from a few known numeric choices.
choice-labels
Control flow can map a small code to a readable label. Simple branches keep the choice explicit and traceable.
Choice Labels
ChoiceLabels.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val code = 2
var label = "other"
if (code == 1) {
label = "start"
}
if (code == 2) {
label = "middle"
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 1
var label = "other"
if (code == 1) {
label = "start"
}
if (code == 2) {
label = "middle"
}
println("code=" + code)
println("label=" + label)
}
}
object Main {
def main(args: Array[String]): Unit = {
val code = 3
var label = "other"
if (code == 1) {
label = "start"
}
if (code == 2) {
label = "middle"
}
println("code=" + code)
println("label=" + label)
}
}
code ← 2, label ← other
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 2 = 2 //@code=1, 34 var label→ other = "other"56 if (code == 1) {label ← middle
8}9if (code2 == 2) {10 label→ middle = "middle"11}println("code=" + code)
13 println("code=" + code2)14 println("label=" + labelmiddle)15 }16}outputcode=2 label=middle
code ← 1, label ← other
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 1 = 14 var label→ other = "other"56 if (code == 1) {label ← start
6if (code1 == 1) {7 label→ start = "start"8}9if (code == 2) {println("code=" + code)
13 println("code=" + code1)14 println("label=" + labelstart)15 }16}outputcode=1 label=start
code ← 3, label ← other
1object Main {2 def main(args: Array[String]): Unit = {3 val code→ 3 = 34 var label→ other = "other"56 if (code == 1) {7 label = "start"8 }9 if (code == 2) {10 label = "middle"11 }1213 println("code=" + code3)14 println("label=" + labelother)15 }16}outputcode=3 label=other
Follow the Labels
codestarts at2.labelstarts as"other".- The
code == 1check is false, solabelstays"other". - The
code == 2check is true, solabelchanges to"middle". - The program prints
code=2andlabel=middle. | code | first check | second check | final label | | --- | --- | --- | --- | | 1 | set to start | no change | start | | 2 | no change | set to middle | middle | | 3 | no change | no change | other |
Exercise: ChoiceLabels.scala
Reproduce label=middle for code 2, then try code 1 and code 3 and predict the final label before running each one.