The when expression in Kotlin is a powerful control structure that allows developers to execute different blocks of code based on the value of a variable. It serves as an elegant replacement for the traditional switch statement found in languages like Java and C++. The when expression not only enhances code readability but also simplifies complex conditional logic, making it a favorite among Kotlin developers.
Why Use `when`?
In programming, conditions are everywhere. You often need to execute different code paths based on certain values. The when expression allows you to handle multiple conditions in a cleaner and more expressive way compared to using several if-else statements. This feature makes your code easier to understand and maintain.
When to Use `when`
- When you have a single variable that you'd like to compare against multiple constant values.
- When you want to check ranges or collections efficiently.
- When you need to execute different actions based on the result of a condition.
Concept Explanation
Think of the when expression as a decision-making tool. Imagine you’re at a restaurant, and the waiter asks what you’d like to order. Depending on your choice, the waiter has a different response:
- If you say "pizza," they might say "Great choice! Would you like extra cheese?"
- If you say "salad," they might respond, "Healthy choice!"
- If you say "soda," they might say, "Would you like that with ice?"
In programming, the when expression works similarly. You provide a value, and the when structure checks that value against predefined cases, executing the code that matches.
Comparison to Other Languages
Here’s a brief comparison of how when would differ from a switch statement in Java:
| Feature | Java switch |
Kotlin when |
|---|---|---|
| Expression vs Statement | Generally a statement | Can be used as an expression |
| Fall-through behavior | Automatically falls through cases | No fall-through; each case is separate |
| Range Checking | Not supported | Supports ranges using in |
| Multiple Case Handling | Requires separate cases | Can handle multiple cases with commas |
Basic Syntax
Here's the basic syntax of the when expression:
when (variable) {
value1 -> { /* code block */ }
value2 -> { /* code block */ }
else -> { /* code block for default case */ }
}
-
variable: The value being evaluated. -
value1,value2: Possible values to match against the variable. -
->: Indicates the action to perform if a case matches. -
else: Acts as a catch-all for any values not explicitly handled.
Working Examples
Example 1: Simple `when` Expression
fun main() {
val dayOfWeek = 3
val dayName = when(dayOfWeek) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
println("The day is $dayName")
}
Output:
The day is Wednesday
Example 2: `when` as a Statement
fun main() {
val score = 85
when(score) {
in 90..100 -> println("Grade: A")
in 80..89 -> println("Grade: B")
in 70..79 -> println("Grade: C")
else -> println("Grade: D or F")
}
}
Output:
Grade: B
Example 3: Multiple Statements in `when`
fun main() {
val month = 4
when(month) {
1 -> {
println("January")
println("It's the start of the year")
}
4 -> {
println("April")
println("Spring is in full bloom")
}
12 -> {
println("December")
println("Winter is here")
}
else -> println("Not a recognized month")
}
}
Output:
April
Spring is in full bloom
Example 4: Handling Multiple Cases
fun main() {
val temperature = 30
when (temperature) {
in 0..15 -> println("It's cold outside.")
in 16..25 -> println("It's a pleasant day.")
in 26..35 -> println("It's warm!")
else -> println("It's hot!")
}
}
Output:
It's warm!
Example 5: Checking Types with `when`
fun main() {
val input: Any = "Hello"
when (input) {
is String -> println("It's a string of length ${input.length}")
is Int -> println("It's an integer: $input")
is Double -> println("It's a double: $input")
else -> println("Unknown type")
}
}
Output:
It's a string of length 5
Common Mistakes
- Forgetting the
elsebranch: If none of the branches match and there is noelse, your program will throw an error. Always include anelsebranch to handle unexpected cases. - Misusing ranges: Ensure the correct use of the
inoperator when checking ranges.
// Incorrect
when (number) {
1 -> println("One")
2 -> println("Two")
// No else branch, this may cause an error for other values
}
// Incorrect
when (number) {
1..5 -> println("Between 1 and 5") // This won't work
}
Correct Approach:
when {
number in 1..5 -> println("Between 1 and 5")
}
Best Practices
- Use
whenas an expression: Take advantage of the ability to assign a value directly from awhenexpression. - Group similar cases: If multiple cases lead to the same result, group them together using commas for cleaner code.
- Leverage ranges: Use the
inoperator to check ranges, enhancing readability and efficiency. - Keep it simple: Avoid overly complex
whenexpressions. If it gets too complicated, consider refactoring it into a function.
Practice Exercises
- Season Checker: Create a program that takes a month number (1-12) and prints the corresponding season (Winter, Spring, Summer, or Autumn).
- Traffic Light System: Simulate a traffic light system where you input a light color (Red, Yellow, Green) and print the action (Stop, Caution, Go).
- Grade Calculator: Write a program that accepts a percentage score and uses a
whenexpression to assign a grade (A, B, C, D, F) based on the score ranges.
These exercises will help you solidify your understanding of the when expression and its practical applications in Kotlin programming. Happy coding!