Sling Academy
Home/Kotlin/What is the `when` Expression in Kotlin?

What is the `when` Expression in Kotlin?

Last updated: December 05, 2024

The when expression in Kotlin is a powerful control flow structure that resembles the switch statement in many other programming languages but with much more flexibility and capability. It evaluates an expression and executes a block of code among many possibilities.

Unlike traditional switch statements, a when expression in Kotlin can be used as both a statement (to execute a set of instructions based on conditions without returning a result) and an expression (that returns a value). This makes it incredibly versatile for various programming scenarios.

Basic Usage

The basic syntax of a when statement in Kotlin is simple:


val x = 3
when (x) {
    1 -> println("x is 1")
    2 -> println("x is 2")
    else -> println("x is neither 1 nor 2")
}

In this example, if x is 1, it prints "x is 1"; if it’s 2, it prints "x is 2". If x isn't 1 or 2, the else branch executes.

Using When as an Expression

One of the most powerful aspects of when is its ability to return a value, making it a true expression:


val y = 6
val result = when (y) {
    1 -> "One"
    2 -> "Two"
    3, 4, 5 -> "Three, Four or Five"
    else -> "Unknown"
}
println(result)

This assignment will store the result "Unknown" in result, since y is not within the cases 1 to 5.

Combining Multiple Values

You can handle multiple possible matches in a single branch by listing multiple comma-separated values:


val day = "Saturday"
val typeOfDay = when (day) {
    "Saturday", "Sunday" -> "Weekend"
    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday"
    else -> "Invalid day"
}
println(typeOfDay)

In this code, you use several literal values in each branch to determine the type of the day.

Handling Ranges and Conditions

when in Kotlin can also work with ranges and conditions seamlessly:


val num = 7
val sizeDescription = when (num) {
    in 1..5 -> "Small"
    in 6..10 -> "Medium"
    else -> "Large"
}
println(sizeDescription)

This handles numeric ranges. The value 7 falls into the "Medium" category, defined by the range 6..10.

Comparing with Other Types

You can also use when with types:


fun describe(obj: Any): String = when (obj) {
    is Int -> "This is an integer"
    is String -> "This is a string"
    else -> "Unknown type"
}

println(describe(123))      // Outputs: This is an integer
println(describe("hello")) // Outputs: This is a string
println(describe(12.34))     // Outputs: Unknown type

In this function, the when expression checks the type of the parameter and returns a descriptive string.

Null Checks Using When

The when expression is also handy in handling null values:


val nullableString: String? = null
val result = when (nullableString) {
    null -> "Value is null"
    else -> "Value is not null"
}
println(result)

This will safely check for null without running into a null pointer exception, returning "Value is null" if nullableString is indeed null.

Exhaustive when Expressions

For when to be used as an expression and not just a statement, it should cover all possible cases. Such expression is called exhaustive. A typical case is dealing with sealed classes:


sealed class Shape {
    object Circle: Shape()
    object Square: Shape()
}

fun describe(shape: Shape): String = when (shape) {
    is Shape.Circle -> "Circle shape"
    is Shape.Square -> "Square shape"
}

The compiler checks that all subclasses of Shape are included in the expression, so there's no need for an else branch.

The Kotlin when expression exemplifies how the language emphasizes safety and simplicity. Whether you're doing simple condition checks or more complex type checking and pattern matching, Kotlin's when is a go-to tool that offers both functionality and readability, contributing to clean, efficient coding.

Next Article: Using `when` as a Replacement for `if-else` Chains in Kotlin

Previous Article: Combining Multiple Conditions with Logical Operators in Kotlin

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin
  • Combining Safe Calls with Collections in Kotlin