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

temperature
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")
}
  1. 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
  1. 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
  1. 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

  1. temperature starts at 72.
  2. Kotlin checks whether temperature >= 80.
  3. 72 is below 80, so the else branch is chosen.
  4. status becomes comfortable.
  5. The program prints temperature=72 and status=comfortable. | temperature | check | status | | --- | --- | --- | | 55 | 55 >= 80 is false | comfortable | | 72 | 72 >= 80 is false | comfortable | | 90 | 90 >= 80 is true | warm |

Exercise: Conditionals.kt

Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.