Skip to content
DeveloperMemos

Checking For Multiple Cases with Kotlin's when

Kotlin, Android Development1 min read

The when expression in Kotlin is a powerful feature that allows you to perform conditional checks on a given value and execute different blocks of code based on various cases. It serves as a more concise alternative to the traditional switch statement in languages like Java.

One of the key advantages of using when is its ability to handle multiple cases with ease. In this article, we'll explore how you can leverage this feature to simplify your code and make it more readable. Let's dive in with some examples.

Example 1: Handling Different Types

Consider a scenario where you have a function that takes an argument of type Any and you need to perform specific actions based on the type of the input. Instead of using nested if-else statements or multiple instanceof checks, you can use when to achieve the same result in a more concise manner.

1fun processInput(input: Any) {
2 when (input) {
3 is String -> println("Input is a string: $input")
4 is Int -> println("Input is an integer: $input")
5 is Double -> println("Input is a double: $input")
6 else -> println("Unknown input type")
7 }
8}

In this example, the when expression checks the type of the input argument and executes the corresponding block of code. If none of the specified cases match, the else block is executed, indicating an unknown input type.

Example 2: Handling Enumerations

When working with enumerations, the when expression comes in handy to handle different enum values and perform specific actions accordingly. Let's say we have an enum class representing different days of the week.

1enum class DayOfWeek {
2 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
3}
4
5fun analyzeDay(day: DayOfWeek) {
6 when (day) {
7 DayOfWeek.MONDAY -> println("It's Monday!")
8 DayOfWeek.FRIDAY -> println("TGIF!")
9 DayOfWeek.SATURDAY, DayOfWeek.SUNDAY -> println("Weekend vibes!")
10 else -> println("Just another day")
11 }
12}

In this case, the when expression takes a DayOfWeek value and executes the appropriate block of code depending on the day. Multiple cases can be grouped together as shown with SATURDAY and SUNDAY, where the same action is performed for both days.

Example 3: Checking Ranges

The when expression can also be used to check if a value falls within a specific range. This can be useful when dealing with numeric values or other ordered data types.

1fun rateScore(score: Int) {
2 when (score) {
3 in 0..49 -> println("Failed")
4 in 50..59 -> println("Pass")
5 in 60..79 -> println("Good")
6 in 80..100 -> println("Excellent")
7 else -> println("Invalid score")
8 }
9}

In this example, the when expression checks if the score parameter falls within different ranges and prints the corresponding message based on the result.

By using when expressions, you can handle multiple cases efficiently and elegantly in your Kotlin code. It simplifies complex branching logic and improves the readability of your codebase.

Now that you have a good grasp of how to check for multiple cases with Kotlin's when, go ahead and start applying it in your Android development projects to make your code more concise and expressive.