0
0
KotlinHow-ToBeginner · 3 min read

How to Use When in Kotlin: Syntax and Examples

In Kotlin, when is a powerful expression used to replace multiple if-else statements. It checks a value against multiple conditions and executes the matching branch. You can use it as an expression returning a value or as a statement for side effects.
📐

Syntax

The when expression checks a value against several branches. Each branch has a condition and a block of code. If a condition matches, its block runs. You can use else as a default case if no other matches occur.

It can be used as an expression that returns a value or as a statement without returning anything.

kotlin
when (value) {
    condition1 -> action1
    condition2 -> action2
    else -> defaultAction
}
💻

Example

This example shows how to use when to print a message based on a number and also how to return a value from when.

kotlin
fun main() {
    val number = 3

    // Using when as a statement
    when (number) {
        1 -> println("Number is one")
        2 -> println("Number is two")
        3 -> println("Number is three")
        else -> println("Number is unknown")
    }

    // Using when as an expression
    val result = when (number) {
        1 -> "One"
        2 -> "Two"
        3 -> "Three"
        else -> "Unknown"
    }

    println("Result: $result")
}
Output
Number is three Result: Three
⚠️

Common Pitfalls

One common mistake is forgetting the else branch when using when as an expression, which causes a compilation error if not all cases are covered.

Another pitfall is using when without an argument, which requires conditions to be boolean expressions.

kotlin
/* Wrong: Missing else in expression */
// val x = 5
// val result = when (x) {
//     1 -> "One"
//     2 -> "Two"
// } // Error: 'else' branch is required

/* Right: Adding else branch */
val x = 5
val result = when (x) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

/* Using when without argument */
val y = 10
when {
    y % 2 == 0 -> println("Even number")
    y % 2 != 0 -> println("Odd number")
}
Output
Even number
📊

Quick Reference

  • Use when(value) to match a value against conditions.
  • Use else as a fallback for unmatched cases.
  • when can return a value, so assign it to a variable.
  • Without argument, when checks boolean conditions.

Key Takeaways

Use when to replace multiple if-else statements for cleaner code.
Always include an else branch when using when as an expression.
when can be used with or without an argument depending on your needs.
You can return values from when and assign them to variables.
Without an argument, when evaluates boolean conditions in each branch.