Thuta Learning
BasicProgrammingbeginner

If & When Expressions

Relax. We'll talk through this in plain words — no textbook voice.

Programs often need to do different things depending on the situation. Kotlin uses if and when to check conditions. What makes Kotlin's if and when special is that they can be expressions, so you can assign the result value directly into a variable.

kotlin
fun main() {
    val score = 82

    val result = if (score >= 50) "Passed" else "Failed"
    println(result)

    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        in 70..79 -> "C"
        else -> "Needs practice"
    }

    println("Grade: $grade")
}
You should see
Passed Grade: B

Summary

if for simple decisions, when for multiple cases.

Easy traps

  • Getting the range order wrong means you won't get the expected result. For example, if you put in 0..100 at the top, none of the grade ranges after it will ever get reached.
If & When Expressions | Thuta Learning