What is When Expression in Kotlin: Simple Explanation and Example
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:
fun main() {
val number = 3
val result = when (number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown number"
}
println(result)
}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-elsestatements. - Supports checking values, types, and ranges.
- Can be used as an expression that returns a value.
- Has an
elsecase for unmatched conditions.