Kotlin is a modern programming language that blends many paradigm approaches, such as functional and object-oriented programming. One of its robust features is the when expression, which serves a role similar to the switch statement in languages like Java but with more power and flexibility.
In this article, we'll delve into advanced usage of when expressions in Kotlin, including handling ranges, types, and a few more interesting scenarios. These capabilities make your code clearer, safer, and more expressive.
Handling Ranges with when
When expressions can be used to check if a value belongs to a specific range. This is useful for handling situations like validating bounds or categorizing data.
fun checkRange(value: Int): String {
return when (value) {
in 1..10 -> "One to ten"
in 11..20 -> "Eleven to twenty"
!in 21..30 -> "Not in twenty-one to thirty"
else -> "Out of range"
}
}
In the example above, we utilise the in keyword to check if a value falls between given ranges. The example evaluates the value, and the corresponding string is returned based on what range the value falls into.
Type Checking with when
Kotlin embraces type safety and provides a straightforward syntax to check against multiple types using when. This is achieved by leveraging smart casts.
fun detectType(obj: Any): String {
return when (obj) {
is String -> "It's a String with length: " + obj.length
is Int -> "It's an Integer"
is Double -> "It's a Double"
else -> "Unknown type"
}
}
Using the is keyword, the when expression can differentiate between types, leveraging Kotlin's smart cast feature to access the object's properties directly after type checking.
Combining Conditions
Sometimes, you need to evaluate multiple conditions to determine the correct branch in a when block. Kotlin provides a convenient way to combine multiple checks using commas.
fun evaluateNumber(number: Int): String {
return when (number) {
0, 1 -> "Zero or One"
10, 20, 30 -> "A multiple of ten"
else -> "Default"
}
}
This demonstrates how you can group various matching criteria into a single branch. The expression 0, 1 -> results in "Zero or One" if number is either 0 or 1.
Using when Without an Argument
The when expression can also be used without checking any specific argument, turning it into a versatile replacement for if-else chains.
fun categorizeAge(age: Int): String {
return when {
age < 18 -> "Minor"
age in 18..64 -> "Adult"
age > 64 -> "Senior"
else -> "Unknown Age"
}
}
Here, when evaluates conditions sequentially, similar to how if-else statements operate, until one is satisfied.
Enumerations and when
Kotlin's when nicely complements enumeration classes by making it easy to match enum constants.
enum class Season { WINTER, SPRING, SUMMER, FALL }
fun getSeasonActivities(season: Season) = when (season) {
Season.WINTER -> "Skiing"
Season.SPRING -> "Picnic"
Season.SUMMER -> "Swimming"
Season.FALL -> "Hiking"
}
This ensures every possible case of the Season enum is accounted for at compile time.
Conclusion
The when expression in Kotlin is powerful, versatile, and expressive. It enhances code readability and safety by preventing oversight in logical paths your application may take. By using its support for ranges, type checking, condition combinations, and enums, you can employ when expressions in almost every decision-making scenario in your Kotlin programs.