← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 1 of 7

if as an Expression

In Kotlin, an if can not only choose which code to run, it can also directly hand back a value, like answering a question.

if as a Statement

The familiar form of if runs one block of code or another based on a condition, without producing any value itself -- this is how if behaves in many other languages.

Example: if as a Statement

markup
fun main() {
    val age = 20
    if (age >= 18) {
        println("You are an adult")
    } else {
        println("You are a minor")
    }
}

if as an Expression

Kotlin also lets if produce a value directly, where the last expression in each branch becomes the result. This lets you assign the outcome straight to a val.

Note: Using if as an expression avoids declaring a var just to be set inside each branch.

Example: if as an Expression

markup
fun main() {
    val age = 20
    val status = if (age >= 18) "adult" else "minor"
    println("Status: $status")
}

Multi-Branch if Expressions

Chaining else if lets an if expression cover more than two outcomes, with the last matching branch's final line providing the resulting value.

Example: Multi-Branch if Expressions

markup
fun main() {
    val score = 85
    val grade = if (score >= 90) "A"
                else if (score >= 80) "B"
                else if (score >= 70) "C"
                else "F"
    println("Grade: $grade")
}

Block Bodies in if Expressions

Each branch of an if expression can be a multi-line block; the last statement inside that block becomes the value contributed by that branch.

Example: Block Bodies in if Expressions

markup
fun main() {
    val number = 7
    val description = if (number % 2 == 0) {
        val kind = "even"
        "The number is $kind"
    } else {
        "The number is odd"
    }
    println(description)
}
Common Mistakes
  1. Writing if only as a statement out of old habit, then separately assigning a variable in each branch instead of using it as an expression.
  2. Forgetting that an if used as an expression needs an else branch, or the compiler cannot guarantee a value in every case.
  3. Putting side effects (like printing) inside an if expression that is also supposed to return a clean value, mixing concerns.
Chapter Summary
  • In Kotlin, if can be used as a statement (to choose which block runs) or as an expression (to produce a value).
  • When used as an expression, every branch's last line is the value produced by that branch.
  • An if expression must have an else branch to guarantee it always produces a value.
  • Using if as an expression often eliminates the need for a separate mutable variable.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.