Start Coding

Topics

Kotlin When Expression

The when expression is a versatile control flow statement in Kotlin. It serves as a more powerful and flexible alternative to the traditional switch statement found in many other programming languages.

Basic Syntax

The basic syntax of a when expression is as follows:

when (expression) {
    value1 -> result1
    value2 -> result2
    else -> defaultResult
}

The when expression evaluates the given expression and compares it against the provided branches. When a match is found, the corresponding code block is executed.

Using When as an Expression

One of the key features of Kotlin's when is its ability to be used as an expression, returning a value:

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

Multiple Conditions

The when expression allows you to check multiple conditions in a single branch:

when (x) {
    0, 1 -> println("x is 0 or 1")
    in 2..10 -> println("x is between 2 and 10")
    else -> println("x is outside the range")
}

Using When Without an Argument

Kotlin's when can also be used without an argument, functioning as a replacement for an if-else chain:

when {
    x < 0 -> println("x is negative")
    x == 0 -> println("x is zero")
    else -> println("x is positive")
}

Smart Casts with When

The when expression works seamlessly with Kotlin's Smart Casts, allowing for type checking and casting in a single operation:

fun describe(obj: Any): String =
    when (obj) {
        is Int -> "It's an integer: $obj"
        is String -> "It's a string of length ${obj.length}"
        is List<*> -> "It's a list with ${obj.size} elements"
        else -> "Unknown type"
    }

Best Practices

  • Use when instead of long if-else chains for improved readability.
  • Leverage the power of when as an expression to write more concise code.
  • Always include an else branch to handle unexpected cases, unless you're certain all possible cases are covered.
  • Take advantage of when's ability to check multiple conditions in a single branch for more efficient code.

Related Concepts

To further enhance your understanding of Kotlin's control flow, explore these related topics:

By mastering the when expression, you'll be able to write more expressive and concise Kotlin code, handling complex conditional logic with ease.