Kotlin If Else

The if...else statement lets your Kotlin program make decisions, and unlike in many other languages, it can also be used directly as an expression that produces a value.

The Basic if Statement

In Kotlin, the if statement executes a block of code only when a specified condition evaluates to true. The condition must be a Boolean expression, and unlike Java or C, Kotlin does not allow integers or other types to be used as a substitute for a Boolean condition.

Basic if

fun main() {
    val temperature = 30

    if (temperature > 25) {
        println("It's a hot day")
    }
}

Adding else

The else branch runs when the if condition is false. Together, if and else let you cover both outcomes of a binary decision without repeating logic.

if...else

fun main() {
    val age = 16

    if (age >= 18) {
        println("You can vote")
    } else {
        println("You cannot vote yet")
    }
}

Chaining with else if

When you need to test several conditions in sequence, chain else if clauses. Kotlin evaluates each condition from top to bottom and executes the first branch whose condition is true, skipping the rest.

  • Conditions are checked in order, top to bottom.
  • Only the first matching branch runs — the rest are skipped.
  • The final else acts as a catch-all for anything not matched above.

else if chain

fun main() {
    val score = 72

    if (score >= 90) {
        println("Grade: A")
    } else if (score >= 75) {
        println("Grade: B")
    } else if (score >= 60) {
        println("Grade: C")
    } else {
        println("Grade: F")
    }
}

if as an Expression

This is where Kotlin diverges from languages like Java. Because if is an expression, it can return a value directly, which you can assign to a variable or return from a function. When used this way, an else branch is required so that the expression always produces a value.

if as an expression

fun main() {
    val a = 10
    val b = 20

    val max = if (a > b) a else b

    println("The larger number is $max")
}
Note: When if is used as an expression, every branch must produce a compatible type, and the else branch is mandatory — the compiler needs to guarantee a value comes out no matter which path is taken.
StyleReturns a value?else required?
if as a statementNoNo
if as an expressionYesYes
if...else if chain (statement)NoNo, but recommended
Note: Watch your braces. Omitting curly braces around a single-statement branch is legal in Kotlin, but it can make else if chains harder to read and easier to misindent — most style guides recommend always using braces.

Exercise: Kotlin If Else

Can an if/else block be used as an expression whose value is assigned to a variable?