Skip to content
DeveloperMemos

Using return with when in Kotlin

Kotlin, Android Development2 min read

When developing Android applications using Kotlin, it's essential to have a good understanding of control flow statements. One powerful construct in Kotlin is the when expression, which provides a concise way to handle multiple cases. In this article, we will explore how to enhance the functionality of the when expression by using the return keyword. By leveraging return within when, you can achieve more fine-grained control over control flow and simplify your code. Let's dive in!

Basic Usage of when

The when expression in Kotlin is similar to a switch statement in other programming languages, but it offers more flexibility and expressiveness. Here's a basic example that demonstrates the usage of when:

1fun processNumber(number: Int) {
2 when (number) {
3 0 -> println("Zero")
4 1 -> println("One")
5 2 -> println("Two")
6 else -> println("Other")
7 }
8}

In the above code snippet, we use when to match against different values of the number parameter. If number is 0, "Zero" will be printed. If number is 1 or 2, "One" or "Two" will be printed, respectively. For any other value, "Other" will be printed.

Returning Values with when

By default, the when expression doesn't return a value. However, you can use the return keyword to make it return a specific value. This can be useful when you need the when expression to determine a result and exit the containing function or block. Here's an example that demonstrates how to return values with when:

1fun getMessage(number: Int): String {
2 return when (number) {
3 0 -> "Zero"
4 1 -> "One"
5 2 -> "Two"
6 else -> "Other"
7 }
8}

In this code snippet, the getMessage function takes an integer parameter number and returns a corresponding message based on its value. By using return with when, we can directly return the desired message from within the expression.

Early Exit with return

Apart from returning a specific value, the return statement can also be used to exit early from a function or block within the when expression. This can be helpful in scenarios where you want to terminate the execution based on certain conditions. Let's take a look at an example:

1fun processNumber(number: Int) {
2 when (number) {
3 in 0..10 -> {
4 println("Number is between 0 and 10")
5 return
6 }
7 in 11..20 -> {
8 println("Number is between 11 and 20")
9 return
10 }
11 }
12 println("Number is greater than 20")
13}
14
15processNumber(5) // Output: Number is between 0 and 10

In the above code snippet, the processNumber function checks if the number falls within specific ranges. If the condition matches, a message is printed, and the return statement causes the function to exit immediately. This allows us to handle specific cases without executing any unnecessary code.

Using when with Sealed Classes

Sealed classes are a powerful feature in Kotlin for representing restricted class hierarchies. They work exceptionally well when combined with the when expression. By utilizing the return keyword, we can achieve exhaustive when branches, ensuring that all possible cases are handled. Here's an example:

1sealed class Result
2data class Success(val data: String) : Result()
3object Error : Result()
4
5fun processResult(result: Result): String {
6 return when (result) {
7 is Success -> {
8 val processedData = processData(result.data)
9 "Success: $processedData"
10 }
11 Error -> "Error occurred"
12 }
13}
14
15fun processData(data: String): String {
16 // Perform data processing here
17 return "[Processed] $data"
18}

In this code snippet, we define a sealed class Result, which has two subclasses: Success and Error. The processResult function takes a Result parameter and processes it accordingly. By using return within the whenexpression, we can handle each case explicitly. If the Result is of type Success, we process the data and return a success message. If it's of type Error, we simply return an error message.

In Closing

The when expression in Kotlin provides a powerful way to handle multiple cases in a concise and expressive manner. By using the return keyword within when, you can enhance its functionality and achieve more fine-grained control over control flow. Whether you need to return values or exit early from a function, return with when can simplify your code and make it more readable. Experiment with these concepts in your Android development projects and leverage the full potential of Kotlin!