In Kotlin, the when
expression is used as a replacement for the traditional switch-case
statement in other programming languages. It is a versatile and powerful tool for handling multiple conditions in a concise and readable way.
The basic syntax for using the when
expression is as follows:
1 2 3 4 5 6 7 8 9 10 11 |
when (variable) { value1 -> { // code block executed when variable matches value1 } value2 -> { // code block executed when variable matches value2 } else -> { // code block executed when variable does not match any of the above values } } |
Here, variable
represents the value or expression to be evaluated against different cases. Each value
is compared with the variable
, and when a match is found, the corresponding code block is executed. If none of the values match, the code block under else
is executed.
Additionally, the when
expression supports multiple conditions in a single code block by separating them with a comma. For example:
1 2 3 4 5 6 7 8 9 10 11 |
when (variable) { value1, value2 -> { // code block executed when variable matches either value1 or value2 } value3 -> { // code block executed when variable matches value3 } else -> { // code block executed when variable does not match any of the above values } } |
Furthermore, the when
expression can also be used without an argument. In this case, it acts as an alternative to if-else if
chains. For example:
1 2 3 4 5 6 7 8 9 10 11 |
when { condition1 -> { // code block executed when condition1 is true } condition2 -> { // code block executed when condition2 is true } else -> { // code block executed when none of the conditions are true } } |
The when
expression in Kotlin is not limited to fixed values or conditions. It can also be used with more complex expressions, ranges, types, and even custom classes to handle different cases in a flexible manner.
Overall, the when
expression is a powerful feature of Kotlin that simplifies conditional expressions and enhances code readability.
How to use the 'when' expression with sealed classes in Kotlin?
To use the when
expression with sealed classes in Kotlin, follow these steps:
- Define a sealed class by using the sealed modifier before the class declaration. This ensures that all subclasses of the sealed class are declared within the same file.
1
|
sealed class Result
|
- Create subclasses of the sealed class using the object or data keyword.
1 2 |
data class Success(val message: String) : Result() data class Error(val code: Int) : Result() |
- Use the when expression to handle different cases based on the subclasses of the sealed class.
1 2 3 4 5 6 |
fun handleResult(result: Result) { when (result) { is Success -> println("Success: ${result.message}") is Error -> println("Error: ${result.code}") } } |
In the above example, the handleResult()
function takes a parameter of type Result
(the sealed class). Inside the when
expression, you can use is
to check the type of the result
parameter and perform different actions accordingly.
Note that when using sealed classes with when
, if you handle all the subclasses, you don't need an else
branch as the when
expression is exhaustive.
How to handle exhaustive 'when' expressions in Kotlin?
In Kotlin, when expressions are a powerful way to handle exhaustive conditions by matching an expression against multiple possible values. However, there are cases when you need to handle a large number of possible values, which can make the code cumbersome to write and read. To handle such exhaustive expressions more efficiently, you can follow these approaches:
- Use ranges: If the possible values are sequential, you can use ranges in place of individual values. For example:
1 2 3 4 5 |
when (x) { in 1..10 -> println("Value between 1 and 10") in 11..20 -> println("Value between 11 and 20") // ... } |
- Group values using commas: If some values have the same response, you can group them together separated by commas. For example:
1 2 3 4 5 |
when (x) { 1, 2, 3 -> println("Value is 1, 2, or 3") 4, 5, 6 -> println("Value is 4, 5, or 6") // ... } |
- Use 'else' clause: If there are remaining values that don't fit into any specific conditions, you can use the 'else' clause to handle them. It acts as a catch-all for unmatched values. For example:
1 2 3 4 5 |
when (x) { in 1..10 -> println("Value between 1 and 10") in 11..20 -> println("Value between 11 and 20") else -> println("Value out of range") } |
- Create named constants: If the exhaustive conditions are repeated in multiple places, you can define named constants to keep the code clean and maintainable. For example:
1 2 3 4 5 6 7 8 |
val RANGE_1_TO_10 = 1..10 val RANGE_11_TO_20 = 11..20 when (x) { in RANGE_1_TO_10 -> println("Value between 1 and 10") in RANGE_11_TO_20 -> println("Value between 11 and 20") // ... } |
By utilizing these techniques, you can handle exhaustive 'when' expressions in a more concise and readable manner.
What is the difference between 'when' and 'switch' statements in Java?
In Java, both when
and switch
are control flow statements that allow you to perform different actions based on different conditions. However, there are some key differences between the two:
- Syntax: switch statements use the syntax: switch (expression) { case value1: // code block break; case value2: // code block break; default: // code block } when statements use the syntax: when (expression) { value1 -> result1 value2 -> result2 else -> result }
- Expression type: switch statements can use a byte, short, char, or int (primitive types) and also strings and enums as the expression. when statements support any type of expression, including primitive types, strings, enums, and objects.
- Matching conditions: switch statements use exact matching conditions (==) for primitive types and enums, and equals() method for strings. when statements use pattern matching conditions (->) which can be customized by overriding the equals() method in the related class.
- Execution flow: switch statements execute the first matching case and execute all subsequent cases unless a break statement is encountered. when statements execute the block associated with the first matching condition and terminate the execution without executing any further condition checks.
- Additional features: switch statements can use the default keyword to specify a default case if none of the cases match. when statements can use the else keyword to specify a default value or behavior if none of the conditions match.
Overall, switch
statements are more traditional and suitable for basic cases with a limited set of conditions. On the other hand, when
statements are more flexible and powerful, especially when working with complex types and custom matching conditions. Note that when
statements were introduced in Java 12 as part of the Java feature preview.