Control Flow
If Expressions
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
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)
}
}
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
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
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
temperaturestarts at68.- Scala checks whether
temperature >= 75. 68is below75, so theelsevalue"cool"is chosen.- The program prints
temperature=68, thenstatus=cool. | temperature | check | chosen status | | --- | --- | --- | | 55 |55 >= 75is false | cool | | 68 |68 >= 75is false | cool | | 85 |85 >= 75is 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.