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

code
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)
  }
}
  1. 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) {
  2. label ← middle

    8}9if (code2 == 2) {10  label→ middle = "middle"11}
  3. println("code=" + code)

    13    println("code=" + code2)14    println("label=" + labelmiddle)15  }16}
    outputcode=2
    label=middle
  1. 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) {
  2. label ← start

    6if (code1 == 1) {7  label→ start = "start"8}9if (code == 2) {
  3. println("code=" + code)

    13    println("code=" + code1)14    println("label=" + labelstart)15  }16}
    outputcode=1
    label=start
  1. 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

  1. code starts at 2.
  2. label starts as "other".
  3. The code == 1 check is false, so label stays "other".
  4. The code == 2 check is true, so label changes to "middle".
  5. The program prints code=2 and label=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.