Exploring Kotlin’s ‘when’ Expressions
Kotlin’s when
expression is a powerful replacement for the traditional switch statement, offering more flexibility and cleaner syntax.
Basic Usage
Simple when Expression
fun getDayName(day: Int): String {
return when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
}
Multiple Conditions
fun getSeason(month: Int): String {
return when (month) {
12, 1, 2 -> "Winter"
3, 4, 5 -> "Spring"
6, 7, 8 -> "Summer"
9, 10, 11 -> "Fall"
else -> "Invalid month"
}
}
Advanced Features
Range Matching
fun getGrade(score: Int): String {
return when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
in 60..69 -> "D"
in 0..59 -> "F"
else -> "Invalid score"
}
}
Type Checking
fun processValue(value: Any): String {
return when (value) {
is String -> "String: ${value.length} characters"
is Int -> "Integer: ${value * 2}"
is Double -> "Double: ${value.toInt()}"
is Boolean -> "Boolean: ${!value}"
else -> "Unknown type"
}
}
Smart Casts
fun processShape(shape: Shape): Double {
return when (shape) {
is Circle -> shape.radius * 2 * Math.PI
is Rectangle -> 2 * (shape.width + shape.height)
is Triangle -> shape.base * shape.height / 2
else -> 0.0
}
}
Best Practices
- Use
when
as an expression when possible - Keep conditions simple and readable
- Use ranges and type checks effectively
- Consider using sealed classes for exhaustive checks
- Use
when
without argument for complex conditions
Common Patterns
Enum Matching
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun getDirectionVector(direction: Direction): Pair<Int, Int> {
return when (direction) {
Direction.NORTH -> Pair(0, 1)
Direction.SOUTH -> Pair(0, -1)
Direction.EAST -> Pair(1, 0)
Direction.WEST -> Pair(-1, 0)
}
}
Complex Conditions
fun getDiscount(customer: Customer, purchase: Purchase): Double {
return when {
customer.isVIP -> 0.2
purchase.amount > 1000 -> 0.15
purchase.items.size > 5 -> 0.1
customer.isNewCustomer -> 0.05
else -> 0.0
}
}
Performance Considerations
when
expressions are compiled to efficient bytecode- Use
when
instead of if-else chains for better readability - Consider using
when
with sealed classes for compile-time safety
Conclusion
Kotlin’s when
expression is a versatile and powerful feature that makes your code more readable and maintainable. Use it to replace traditional switch statements and complex if-else chains.