Guide to the “when{}” Block in Kotlin

Table of Contents

Introduction

In Kotlin, the “when” expression is a powerful construct used for conditional branching. It is similar to the traditional “switch” statement in other programming languages, but with more flexibility and enhanced features. The “when” expression allows you to check an expression against multiple branches and execute the code block associated with the first matching branch. In this article, we’ll explore the “when{}” block in Kotlin, its syntax, features, and how it can be used effectively.

Syntax of “when{}” Block

The basic syntax of the “when” expression in Kotlin is as follows:

when (variable) {
    value1 -> {
        // Code to execute when variable is equal to value1
    }
    value2 -> {
        // Code to execute when variable is equal to value2
    }
    value3, value4 -> {
        // Code to execute when variable is equal to value3 or value4
    }
    else -> {
        // Code to execute when variable does not match any of the above cases
    }
}

In the above syntax:

  • variable: The expression to be checked against different cases.
  • value1, value2, etc.: The possible values that the variable can take.
  • ->: Separates the value from the corresponding code block.
  • else: An optional branch that executes when none of the previous cases match.

Simple Usage of “when{}” Block

Let’s start with a simple example to demonstrate the basic usage of the “when{}” block:

fun main() {
    val dayOfWeek = 2

    when (dayOfWeek) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        4 -> println("Thursday")
        5 -> println("Friday")
        6 -> println("Saturday")
        7 -> println("Sunday")
        else -> println("Invalid day")
    }
}

In this example, we have a variable dayOfWeek with a value of 2. The “when{}” block checks the value of dayOfWeek against different cases and prints the corresponding day of the week. Since dayOfWeek is equal to 2, the output will be “Tuesday.”

Combining Cases and Ranges

The “when” expression in Kotlin allows you to combine cases and use ranges for more concise and efficient code. For example:

fun main() {
    val score = 85

    when (score) {
        in 90..100 -> println("Excellent")
        in 80 until 90 -> println("Very Good")
        in 70 until 80 -> println("Good")
        in 60 until 70 -> println("Satisfactory")
        else -> println("Needs Improvement")
    }
}

In this example, we use ranges to determine the grade based on the score. If score is between 90 and 100 (inclusive), the output will be “Excellent.” If it’s between 80 and 89 (inclusive), the output will be “Very Good,” and so on.

Smart Casting with “when{}” Block

The “when” expression in Kotlin also supports smart casting, which means that if you use the “is” operator in a branch, you can access the casted value as a variable within the code block. Here’s an example:

fun processValue(value: Any) {
    when (value) {
        is String -> println("Length of the string is ${value.length}")
        is Int -> println("Value is an Integer")
        is Double -> println("Value is a Double")
        else -> println("Unknown type")
    }
}

In this example, the “when{}” block checks the type of value using the “is” operator. If value is a String, it prints the length of the string. If it’s an Int, it indicates that it is an Integer, and if it’s a Double, it indicates that it is a Double.

Using “when{}” Block with Enum Classes

The “when” expression is particularly useful when working with enum classes in Kotlin. It allows you to handle different cases for each enum value easily. Here’s an example:

enum class Color {
    RED, GREEN, BLUE, YELLOW
}

fun getColorDescription(color: Color): String {
    return when (color) {
        Color.RED -> "Warm color associated with energy and passion."
        Color.GREEN -> "Represents nature, growth, and harmony."
        Color.BLUE -> "Symbolizes tranquility, calmness, and stability."
        Color.YELLOW -> "Stands for happiness, positivity, and energy."
    }
}

In this example, we have an enum class Color with different color values. The getColorDescription() function uses the “when{}” block to provide a description for each color.

Using “when{}” Block with Multiple Conditions

The “when” expression in Kotlin allows you to use multiple conditions within a single branch. This feature is especially useful when you want to execute the same code block for different cases. Here’s an example:

fun main() {
    val dayOfWeek = 2

    when (dayOfWeek) {
        1, 2, 3, 4, 5 -> println("Weekday")
        6, 7 -> println("Weekend")
        else -> println("Invalid day")
    }
}

In this example, we combine multiple cases (1, 2, 3, 4, 5) into a single branch to determine if dayOfWeek represents a weekday or a weekend day. The output will be “Weekday” because dayOfWeek is equal to 2.

Using “when{}” Block without an Argument

In Kotlin, you can also use the “when{}” block without an argument. In this case, each branch will have a condition that evaluates to a boolean value. The first branch with a true condition will be executed. Here’s an example:

fun main() {
    val score = 85
    val isPassed = true

    when {
        score >= 90 -> println("Excellent")
        score in 80 until 90 -> println("Very Good")
        score in 70 until 80 -> println("Good")
        score in 60 until 70 -> println("Satisfactory")
        else -> println("Needs Improvement")
    }

    when {
        isPassed -> println("You passed the exam.")
        else -> println("You did not pass the exam.")
    }
}

In the first “when{}” block, we don’t provide an argument. Instead, we use conditions like score >= 90 to determine the grade. The output will be “Very Good” because score is 85.

In the second “when{}” block, we use the boolean isPassed as the condition. Since isPassed is true, the output will be “You passed the exam.”

Using “when{}” Block with Sealed Classes

Sealed classes are a powerful feature in Kotlin that can be used together with the “when” expression. A sealed class is a superclass that can have multiple subclasses but is limited to a specific set of subclasses defined within the same file. This allows you to use the “when{}” block to handle all the possible subclasses of a sealed class. Here’s an example:

sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()
class Loading : Result()

fun processResult(result: Result) {
    when (result) {
        is Success -> println("Data: ${result.data}")
        is Error -> println("Error: ${result.message}")
        is Loading -> println("Loading...")
    }
}

fun main() {
    val successResult = Success("Hello, Kotlin!")
    val errorResult = Error("Failed to load data.")
    val loadingResult = Loading()

    processResult(successResult) // Output: Data: Hello, Kotlin!
    processResult(errorResult) // Output: Error: Failed to load data.
    processResult(loadingResult) // Output: Loading...
}

In this example, we have a sealed class Result with three subclasses: Success, Error, and Loading. The processResult() function uses the “when{}” block to handle each of the subclasses and perform specific actions based on the result type.

Conclusion

The “when{}” block in Kotlin is a versatile and expressive construct that allows you to handle conditional branching in various ways. It can be used with multiple conditions, without an argument, and with sealed classes to create concise and readable code.

By mastering the “when{}” block, you can make your Kotlin programs more structured, efficient, and easy to understand. Its flexibility and power make it a valuable tool in your Kotlin programming toolbox for handling complex conditional scenarios.

Command PATH Security in Go

Command PATH Security in Go

In the realm of software development, security is paramount. Whether you’re building a small utility or a large-scale application, ensuring that your code is robust

Read More »
Undefined vs Null in JavaScript

Undefined vs Null in JavaScript

JavaScript, as a dynamically-typed language, provides two distinct primitive values to represent the absence of a meaningful value: undefined and null. Although they might seem

Read More »