Foundations
Conditionals
An if expression lets Kotlin choose between branches.
if expression
Kotlin `if` can produce a value, so the chosen branch can be assigned to a variable.
Conditionals
Conditionals.kt
Replay: real traced execution (multi-file project)
fun main() {
val temperature = 72
val status = if (temperature >= 80) {
"warm"
} else {
"comfortable"
}
println("temperature=$temperature")
println("status=$status")
}
fun main() {
val temperature = 55
val status = if (temperature >= 80) {
"warm"
} else {
"comfortable"
}
println("temperature=$temperature")
println("status=$status")
}
fun main() {
val temperature = 90
val status = if (temperature >= 80) {
"warm"
} else {
"comfortable"
}
println("temperature=$temperature")
println("status=$status")
}
temperature ← 72, status ← comfortable
1fun main() {2 val temperature→ 72 = 72 //@temperature=55, 903 val status→ comfortable = if (temperature72 >= 80) {4 "warm"5 } else {6 "comfortable"7 }89 println("temperature=$temperature72")10 println("status=$statuscomfortable")11}outputtemperature=72 status=comfortable
temperature ← 55, status ← comfortable
1fun main() {2 val temperature→ 55 = 553 val status→ comfortable = if (temperature55 >= 80) {4 "warm"5 } else {6 "comfortable"7 }89 println("temperature=$temperature55")10 println("status=$statuscomfortable")11}outputtemperature=55 status=comfortable
temperature ← 90, status ← warm
1fun main() {2 val temperature→ 90 = 903 val status→ warm = if (temperature90 >= 80) {4 "warm"5 } else {6 "comfortable"7 }89 println("temperature=$temperature90")10 println("status=$statuswarm")11}outputtemperature=90 status=warm
Follow the Branch
temperaturestarts at72.- Kotlin checks whether
temperature >= 80. 72is below80, so theelsebranch is chosen.statusbecomescomfortable.- The program prints
temperature=72andstatus=comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is true | warm |
Exercise: Conditionals.kt
Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.