In Kotlin, the traditional `
switch
` statement from languages like Java is replaced with the more powerful and flexible `
when
` expression. The `
when
` expression allows you to perform conditional branching based on the value of an expression. It offers a more concise and versatile syntax compared to the `
switch
` statement.
Here's how you can use `when
` as a replacement for `switch
`:1. Simple `when
` Expression :
when (variable) {
value1 -> {
// Code block for value1
}
value2 -> {
// Code block for value2
}
else -> {
// Default code block
}
}​
2. Multiple Values :
when (variable) {
value1, value2 -> {
// Code block for value1 or value2
}
else -> {
// Default code block
}
}​
3. Range Checks :
when (variable) {
in range1 -> {
// Code block for values within range1
}
in range2 -> {
// Code block for values within range2
}
else -> {
// Default code block
}
}
4. Checking Type :
when (variable) {
is Type1 -> {
// Code block for Type1
}
is Type2 -> {
// Code block for Type2
}
else -> {
// Default code block
}
}​
5. Function Calls and Expressions :
when {
condition1() -> {
// Code block if condition1() is true
}
condition2() -> {
// Code block if condition2() is true
}
else -> {
// Default code block
}
}​
The `
when
` expression is more flexible than the traditional `
switch
` statement as it allows for complex conditions, type checks, range checks, and multiple values. It eliminates the need for `
break
` statements and supports more expressive and readable code. Additionally, the `
when
` expression can be used as an expression itself, allowing it to be assigned to a variable or used directly in function return statements.
The `
when
` expression in Kotlin serves as a powerful replacement for the `
switch
` statement, providing enhanced functionality and improved readability.