When vs Switch in Kotlin: Key Differences and Usage
when replaces Java's switch statement and is more powerful and flexible. Unlike switch, when can handle any object type, support complex conditions, and return values directly.Quick Comparison
Here is a quick side-by-side comparison of Kotlin's when and Java's switch statement.
| Feature | Kotlin when | Java switch |
|---|---|---|
| Type support | Any type (Int, String, objects, enums) | Primitive types, enums, and String (Java 7+) |
| Syntax style | Expression (returns value) or statement | Statement only |
| Condition types | Multiple conditions, ranges, predicates | Single value matching |
| Fall-through behavior | No fall-through by default | Fall-through unless break used |
| Null handling | Can handle null explicitly | Cannot switch on null |
| Use cases | Complex branching and value returns | Simple value matching |
Key Differences
The when expression in Kotlin is a versatile replacement for the traditional switch statement found in Java. Unlike switch, which only works with primitive types, enums, and strings, when can evaluate any object type, including complex conditions like ranges and predicates.
Another major difference is that when is an expression, meaning it returns a value directly, which allows for concise and functional-style code. In contrast, switch is a statement and does not return a value, often requiring additional variables to store results.
Also, when does not have fall-through behavior by default, so each case is isolated without needing explicit break statements. This reduces bugs caused by accidental fall-through in switch. Additionally, when can explicitly handle null values, while switch cannot operate on null.
Code Comparison
Here is how you would use Kotlin's when expression to print a message based on a day number, similar to Java's switch statement.
fun printDaySwitch(day: Int) {
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Other day")
}
}
fun main() {
printDaySwitch(2)
}When Equivalent
Here is the equivalent Kotlin when expression doing the same task with more flexibility.
fun printDayWhen(day: Int) {
val dayName = when (day) {
in 1..5 -> "Weekday"
6, 7 -> "Weekend"
else -> "Invalid day"
}
println(dayName)
}
fun main() {
printDayWhen(6)
}When to Use Which
Choose when in Kotlin for all conditional branching because it is more powerful, concise, and safe. It works with any type, supports complex conditions, and returns values directly.
Use switch only if you are working in Java or legacy code that requires it. In Kotlin, when is the modern and recommended approach for all similar use cases.
Key Takeaways
when in Kotlin replaces switch with more power and flexibility.when supports any type, complex conditions, and returns values directly.switch is limited to primitives, enums, and strings with fall-through behavior.when in Kotlin for safer and cleaner conditional logic.switch in Java or legacy contexts.