Foundations
Conditionals
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
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)
}
}
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
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
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
temperaturestarts at72.- Scala checks whether
temperature >= 80. 72 >= 80is false.- The other branch gives
statusthe valuecomfortable. - The program prints
temperature=72andstatus=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.