Choose a value with an if expression.

if-expression An if expression chooses one of two values. The chosen value can be assigned to a name.

If Expressions

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

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

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

    println("temperature=" + temperature)
    println("status=" + status)
  }
}
  1. temperature ← 68, status ← cool

    1object Main {2  def main(args: Array[String]): Unit = {3    val temperature→ 68 = 68 //@temperature=55, 854    val status→ cool = if (temperature68 >= 75) {5      "warm"6    } else {7      "cool"8    }910    println("temperature=" + temperature68)11    println("status=" + statuscool)12  }13}
    outputtemperature=68
    status=cool
  1. temperature ← 55, status ← cool

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

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

Follow the Choice

  1. temperature starts at 68.
  2. Scala checks whether temperature >= 75.
  3. 68 is below 75, so the else value "cool" is chosen.
  4. The program prints temperature=68, then status=cool. | temperature | check | chosen status | | --- | --- | --- | | 55 | 55 >= 75 is false | cool | | 68 | 68 >= 75 is false | cool | | 85 | 85 >= 75 is true | warm |

Exercise: IfExpression.scala

Reproduce status=cool for temperature 68, then try the listed 55 and 85 variants and predict which branch each one chooses.