0
0
KotlinConceptBeginner · 3 min read

What is When Expression in Kotlin: Simple Explanation and Example

The when expression in Kotlin is a powerful way to check a value against multiple conditions, similar to a switch statement in other languages. It lets you run different code blocks based on matching cases, making your code cleaner and easier to read.
⚙️

How It Works

The when expression in Kotlin works like a decision maker that checks a value against several possible options. Imagine you have a box with different colored balls, and you want to do something special depending on the color you pick. The when expression looks at the color and chooses the matching action.

It compares the value you give it to each case you list. When it finds a match, it runs the code for that case and stops checking further. If no case matches, it can run a default action, like a safety net. This makes your code neat because you don’t need many if-else statements.

đź’»

Example

This example shows how to use when to print a message based on a number:

kotlin
fun main() {
    val number = 3
    val result = when (number) {
        1 -> "One"
        2 -> "Two"
        3 -> "Three"
        else -> "Unknown number"
    }
    println(result)
}
Output
Three
🎯

When to Use

Use the when expression when you have one value to check against many possible options. It is perfect for replacing long if-else chains, making your code easier to read and maintain.

For example, you can use it to handle user input choices, respond to different states in your app, or decide actions based on types or ranges of values.

âś…

Key Points

  • Cleaner alternative to multiple if-else statements.
  • Supports checking values, types, and ranges.
  • Can be used as an expression that returns a value.
  • Has an else case for unmatched conditions.
âś…

Key Takeaways

The when expression simplifies checking one value against many cases.
It returns a value, so you can assign its result directly to a variable.
Use else to handle any unmatched cases safely.
It improves code readability compared to long if-else chains.