An if expression lets Scala choose between branches.

if expression Scala `if` can produce a value, so the chosen branch can be assigned to a name.

Conditionals

temperature
Conditionals.scala
Replay: real traced execution (multi-file project)
object Main {
  def main(args: Array[String]): Unit = {
    val temperature = 72
    val status = if (temperature >= 80) {
      "warm"
    } else {
      "comfortable"
    }

    println("temperature=" + temperature)
    println("status=" + status)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val temperature = 55
    val status = if (temperature >= 80) {
      "warm"
    } else {
      "comfortable"
    }

    println("temperature=" + temperature)
    println("status=" + status)
  }
}
object Main {
  def main(args: Array[String]): Unit = {
    val temperature = 90
    val status = if (temperature >= 80) {
      "warm"
    } else {
      "comfortable"
    }

    println("temperature=" + temperature)
    println("status=" + status)
  }
}
  1. temperature ← 72, status ← comfortable

    1object Main {2  def main(args: Array[String]): Unit = {3    val temperature→ 72 = 72 //@temperature=55, 904    val status→ comfortable = if (temperature72 >= 80) {5      "warm"6    } else {7      "comfortable"8    }910    println("temperature=" + temperature72)11    println("status=" + statuscomfortable)12  }13}
    outputtemperature=72
    status=comfortable
  1. temperature ← 55, status ← comfortable

    1object Main {2  def main(args: Array[String]): Unit = {3    val temperature→ 55 = 554    val status→ comfortable = if (temperature55 >= 80) {5      "warm"6    } else {7      "comfortable"8    }910    println("temperature=" + temperature55)11    println("status=" + statuscomfortable)12  }13}
    outputtemperature=55
    status=comfortable
  1. temperature ← 90, status ← warm

    1object Main {2  def main(args: Array[String]): Unit = {3    val temperature→ 90 = 904    val status→ warm = if (temperature90 >= 80) {5      "warm"6    } else {7      "comfortable"8    }910    println("temperature=" + temperature90)11    println("status=" + statuswarm)12  }13}
    outputtemperature=90
    status=warm

What Happens

  1. temperature starts at 72.
  2. Scala checks whether temperature >= 80.
  3. 72 >= 80 is false.
  4. The other branch gives status the value comfortable.
  5. The program prints temperature=72 and status=comfortable.

Branch Picture

| temperature | comparison | status | | --- | --- | --- | | 55 | false | comfortable | | 72 | false | comfortable | | 90 | true | warm |

Exercise: Conditionals.scala

Reproduce status=comfortable for temperature 72, then use the pinned temperatures 55 and 90 to identify each branch.