When as an Expression
Swipe um das Menü anzuzeigen
What Is a 'when' Expression?
A 'when' expression in Kotlin is a flexible way to handle multiple conditions. It is similar to a switch statement in Java, but more powerful and concise. You use it to choose what your code should do based on different values or conditions.
How 'when' Expressions Work
- You provide a value or condition to the
whenkeyword; - Each branch checks if the value matches a specific case;
- The first matching branch runs its code block;
- If no branches match, the
elsebranch runs (if provided).
Using 'when' as an Expression
A 'when' expression can return a value. You can assign the result of a when directly to a variable:
val result = when (number) {
1 -> "One"
2 -> "Two"
else -> "Other"
}
Here, result will hold the string that matches the value of number.
Why Use 'when' Expressions?
- Simplifies complex
if-elsechains; - Improves code readability and maintainability;
- Supports matching multiple values, ranges, or conditions in each branch.
Main.kt
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
When as an Expression
What Is a 'when' Expression?
A 'when' expression in Kotlin is a flexible way to handle multiple conditions. It is similar to a switch statement in Java, but more powerful and concise. You use it to choose what your code should do based on different values or conditions.
How 'when' Expressions Work
- You provide a value or condition to the
whenkeyword; - Each branch checks if the value matches a specific case;
- The first matching branch runs its code block;
- If no branches match, the
elsebranch runs (if provided).
Using 'when' as an Expression
A 'when' expression can return a value. You can assign the result of a when directly to a variable:
val result = when (number) {
1 -> "One"
2 -> "Two"
else -> "Other"
}
Here, result will hold the string that matches the value of number.
Why Use 'when' Expressions?
- Simplifies complex
if-elsechains; - Improves code readability and maintainability;
- Supports matching multiple values, ranges, or conditions in each branch.
Main.kt
Danke für Ihr Feedback!