Kotlin When Expression

Kotlin when expression is used to compare a value or a condition against multiple branches and run the code for the first matching branch. It is commonly used in places where Java developers would use a switch statement, but Kotlin when is more flexible because it can match constants, multiple values, ranges, types, and Boolean conditions.

Kotlin when expression can be related to switch case in Java, but when expression is concise in syntax and extended in functionality.

In this tutorial, we will learn the syntax of Kotlin when expression, how it works as a statement and as an expression, and how to use it with examples such as integer values, strings, multiple branch values, ranges, and type checks.

Using object type of Any with when expression makes is really broad in the usage, where the matching can be done for int, string or any other primitive datatype. We shall learn in detail in our second example.

Kotlin when expression syntax for matching one value

Let us see terminology and working of When expression.

Following is the syntax of Kotlin when expression.

</>
Copy
    when (expression) {
        value_1 -> {
            // set of statements
        }
        value_2 -> {
            // set of statements
        }
        value_n -> {
            // set of statements
        }
        else -> {
            // default set of statements
            // when no value matches the evaluated expression's value
        }
    }

In the above code snippet, the expression in the parenthesis next to the when keyword is evaluated to a value.

The value is matched against the values(value_1, value_2, . . ) written inside the block. When a match happens, the corresponding branch is executed.

If no match happens, and there is an else block is provided inside the when expression, the branch corresponding to the else block is executed.

Note : When there are more than one values that match to the expression’s value, only the branch corresponding to first match is executed. And the program control comes out of the when expression.

Kotlin when branch rules and first-match behavior

Each branch in a Kotlin when block has a condition on the left side and the code to run on the right side of ->. Kotlin checks the branches from top to bottom. Once a matching branch is found, that branch is executed and the remaining branches are skipped.

The else branch is the fallback branch. It runs only when no other branch matches. If you use when as an expression that returns a value, Kotlin generally expects all possible cases to be covered. For simple types such as Int or String, an else branch is usually required when the compiler cannot prove that every possible value is handled.

Kotlin when formUse case
when (value)Match one value against constants, strings, ranges, or type checks.
when without an argumentWrite an if-else-if style chain using Boolean conditions.
when assigned to a variableReturn a value from the matching branch.
else branchHandle values that do not match any earlier branch.

Example 1 – Kotlin When Expression

Following is a simple example for when expression in Kotlin. In the when expression, based on the value of n (nth day of week), we shall print the day of week.

Kotlin Program – example.kt

</>
Copy
fun main(args: Array) {
    printWeekDay(1);
    printWeekDay(2);
    printWeekDay(3);
    printWeekDay(4);
    printWeekDay(5);
    printWeekDay(6);
    printWeekDay(7);
    printWeekDay(12);
}

fun printWeekDay(n: Int){
    when (n) {
        1 -> {
            println("Sunday")
        }
        2 -> {
            println("Monday")
        }
        3 -> {
            println("Tuesday")
        }
        4 -> {
            println("Wednesday")
        }
        5 -> {
            println("Thursday")
        }
        6 -> {
            println("Friday")
        }
        7 -> {
            println("Saturday")
        }
        else -> { // Note the block
            println("Invalid value")
        }
    }
}

Run the above program in your IDE, and you shall get the following output printed to console.

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Invalid value

For the function call, printWeekDay(12), there is no match found. Hence, else block is executed.

In modern Kotlin examples, you may also see the entry point written as fun main() when command-line arguments are not needed. The when logic remains the same.

Kotlin when expression that returns a value

A useful feature of Kotlin when is that it can return a value. This avoids declaring a variable first and then assigning it inside every branch.

Kotlin Program – When returns a String

</>
Copy
fun main() {
    val dayNumber = 3

    val dayName = when (dayNumber) {
        1 -> "Sunday"
        2 -> "Monday"
        3 -> "Tuesday"
        4 -> "Wednesday"
        5 -> "Thursday"
        6 -> "Friday"
        7 -> "Saturday"
        else -> "Invalid day number"
    }

    println(dayName)
}

Output

Tuesday

Here, the matching branch returns a String, and that value is assigned to dayName. Since dayNumber is an Int, the else branch handles numbers outside the range 1 to 7.

Kotlin when with multiple values in the same branch

If two or more values should run the same code, separate those values with commas in a single when branch. This keeps the code shorter and avoids repeated branch bodies.

Kotlin Program – Match multiple values

</>
Copy
fun main() {
    val option = 'y'

    when (option) {
        'y', 'Y' -> println("Yes selected")
        'n', 'N' -> println("No selected")
        else -> println("Invalid option")
    }
}

Output

Yes selected

In this example, both 'y' and 'Y' execute the same branch. Similarly, both 'n' and 'N' execute the second branch.

Kotlin when with ranges using in and !in

Kotlin when can check whether a value belongs to a range or collection using in. To check that a value is outside a range or collection, use !in.

Kotlin Program – Check marks range

</>
Copy
fun main() {
    val marks = 82

    val grade = when (marks) {
        in 90..100 -> "A"
        in 75..89 -> "B"
        in 60..74 -> "C"
        in 35..59 -> "D"
        in 0..34 -> "Fail"
        else -> "Invalid marks"
    }

    println(grade)
}

Output

B

The value 82 lies in the range 75..89, so the branch returns "B". The else branch catches values such as negative marks or marks greater than 100.

Example 2 – Kotlin When with object of type Any

In this example, the variable in the expression is of type “Any”. The variable can be matched with values of any type. The variable n, is matched against values of type Int and String. This could be extended to any of the primitive data types.

Kotlin Program – example.kt

</>
Copy
fun main(args: Array) {
    printWeekDay(1);
    printWeekDay("TUE");
}

fun printWeekDay(n: Any){
    when (n) {
        1 -> {
            println("Sunday")
        }
        "SUN" -> {
            println("Sunday")
        }
        2 -> {
            println("Monday")
        }
        "MON" -> {
            println("Monday")
        }
        3 -> {
            println("Tuesday")
        }
        "TUE" -> {
            println("Tuesday")
        }
        4 -> {
            println("Wednesday")
        }
        "WED" -> {
            println("Wednesday")
        }
    }
}

Run the Kotlin program and you shall get the following output in console.

Output

Sunday
Tuesday

The Any type allows the argument to hold values of different types. In the above example, 1 is matched as an integer value and "TUE" is matched as a string value.

Kotlin when with type checks using is and !is

When the input type is broad, such as Any, you can use is inside when to check the runtime type of the value. After a successful type check, Kotlin smart-casts the value inside that branch.

Kotlin Program – Type check with when

</>
Copy
fun main() {
    printValueInfo("Kotlin")
    printValueInfo(25)
    printValueInfo(12.5)
}

fun printValueInfo(value: Any) {
    when (value) {
        is String -> println("String length: ${value.length}")
        is Int -> println("Integer value: $value")
        is Double -> println("Double value: $value")
        else -> println("Unknown value")
    }
}

Output

String length: 6
Integer value: 25
Double value: 12.5

Inside the is String branch, value can be used as a String, so value.length is valid without an explicit cast.

Kotlin when without an argument for Boolean conditions

You can also write when without passing an expression in parentheses. In that form, each branch condition must evaluate to true or false. This is useful when each branch has a different Boolean condition.

Kotlin Program – When as if-else-if replacement

</>
Copy
fun main() {
    val temperature = 32

    when {
        temperature >= 40 -> println("Very hot")
        temperature >= 30 -> println("Hot")
        temperature >= 20 -> println("Warm")
        else -> println("Cool")
    }
}

Output

Hot

The first condition, temperature >= 40, is false. The next condition, temperature >= 30, is true, so Kotlin executes that branch and skips the rest.

Kotlin when compared with Java switch

Kotlin when is often described as a replacement for Java switch, but it is not limited to simple constant matching. It can be used as an expression, can check ranges, can check types, and does not need a break statement after every branch.

FeatureKotlin whenJava switch
Branch separatorUses ->Traditionally uses case and :
Break after a branchNot requiredOften required in classic switch statements
Return a valueCan be used as an expressionDepends on Java version and syntax used
Ranges and type checksSupported directly with in and isNot handled in the same direct form in classic switch

Common mistakes while using Kotlin when expression

  • Forgetting else when returning a value: If the compiler cannot verify that all possible cases are covered, add an else branch.
  • Putting a broad condition before a specific one: Since when uses first-match behavior, order branches carefully when conditions overlap.
  • Repeating the same branch body: Use comma-separated values when several values should run the same code.
  • Using when where a simple if is clearer: For one simple condition, if may be easier to read.
  • Expecting Java-style fall-through: Kotlin when does not continue into the next branch after a match.

Kotlin when expression editorial QA checklist

  • Check that every when expression used to assign a value covers all expected cases or includes else.
  • Confirm that output blocks show only program output and use the output class.
  • Verify that examples using ranges explain why the selected range matches.
  • Make sure type-check examples use is only where the input type can hold multiple runtime types.
  • Review branch order when using Boolean conditions in when without an argument.

Kotlin when expression FAQs

Is Kotlin when the same as switch in Java?

Kotlin when is commonly used where Java developers might use switch, but it has more features. It can return a value, match multiple values in one branch, check ranges, check types, and work without a subject expression.

Does Kotlin when need a break statement?

No. Kotlin when does not need a break statement. After the first matching branch is executed, control exits the when block automatically.

When is else required in Kotlin when?

else is required when when is used as an expression and Kotlin cannot confirm that all possible values are handled. It is also a good fallback for invalid or unexpected input values.

Can Kotlin when match more than one value in the same branch?

Yes. Write multiple values separated by commas before the arrow. For example, 'y', 'Y' -> println("Yes") runs the same branch for both uppercase and lowercase input.

Can Kotlin when be used without an argument?

Yes. When used without an argument, each branch condition is a Boolean expression. This form works like an ifelse ifelse chain.

Kotlin when expression summary

In this Kotlin Tutorial, we have learnt the syntax of Kotlin when and how to use it for decision making tasks. Kotlin when can match simple values, combine multiple values in one branch, check ranges with in, check types with is, work without an argument for Boolean conditions, and return a value from the matching branch.