The ‘when‘ expression in Kotlin is a powerful and flexible control flow construct that is similar to Java’s ‘switch‘ statement but with several important differences.
In Kotlin, the ‘when‘ expression can be used as an expression or as a statement. When used as an expression, it returns a value that can be assigned to a variable or used in an expression. When used as a statement, it operates like a series of ‘if-else‘ statements.
The basic syntax of the ‘when‘ expression in Kotlin is as follows:
when (input) {
value1 -> doSomething1()
value2 -> doSomething2()
value3, value4 -> doSomething3OrSomething4()
else -> doSomethingElse()
}
Here, ‘input‘ is the value being tested, and each ‘value‘ is a possible input value that can be matched. If a match is found, the corresponding expression or statement is executed. The ‘else‘ block is optional and is executed if no match is found.
One of the key differences between the ‘when‘ expression in Kotlin and the ‘switch‘ statement in Java is that the ‘when‘ expression supports any type of input value, not just ‘int‘ or ‘char‘. This means that you can use the ‘when‘ expression with strings, enums, and even custom types.
Additionally, you can use the ‘when‘ expression with more complex conditions by using a boolean expression as the input value or by combining multiple values using ranges or other operators.
Here’s an example of using a ‘when‘ expression in Kotlin with a custom enum:
enum class Color {
RED, GREEN, BLUE
}
fun getColor(name: String): Color {
return when (name) {
"red" -> Color.RED
"green" -> Color.GREEN
"blue" -> Color.BLUE
else -> throw IllegalArgumentException("Invalid color name")
}
}
In this example, the ‘when‘ expression is used to match the ‘name‘ input value with the corresponding color value in the ‘Color‘ enum. If no match is found, an exception is thrown.
In contrast, here’s an equivalent example using a ‘switch‘ statement in Java:
enum Color {
RED, GREEN, BLUE
}
Color getColor(String name) {
switch(name) {
case "red":
return Color.RED;
case "green":
return Color.GREEN;
case "blue":
return Color.BLUE;
default:
throw new IllegalArgumentException("Invalid color name");
}
}
As you can see, the ‘switch‘ statement only works with ‘String‘ input values if you are using Java 7 or later, and it requires more verbose syntax to achieve the same result as the ‘when‘ expression in Kotlin.