> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin When Expression

The `when` construct in Kotlin is a multi-branch conditional control flow mechanism that evaluates a target subject against a series of branch conditions sequentially until a match is found. It serves as an expression-oriented, type-safe replacement for the traditional `switch` statement found in C-style languages.

Because `when` evaluates top-to-bottom, execution halts at the first successfully evaluated branch. Fall-through behavior does not occur, eliminating the need for `break` statements.

## Expression vs. Statement

`when` can be utilized either as a statement or as an expression.

**As an Expression:**
When the result of the `when` block is assigned to a variable or returned from a function, it is treated as an expression. The compiler enforces **exhaustiveness**, meaning every possible value of the subject's type must be handled. If the compiler cannot guarantee exhaustiveness, an `else` branch is mandatory.

```kotlin theme={"dark"}
val value = 3
val result: String = when (value) {
    1 -> "One"
    2 -> "Two"
    else -> "Unknown" // Mandatory else branch for exhaustiveness
}
```

**Exhaustiveness with Sealed Classes and Enums:**
If the subject is an `enum` class, a `sealed` class/interface, or a `Boolean`, the compiler can verify exhaustiveness at compile time. If all possible cases are covered by the branches, the `else` branch can (and generally should) be omitted.

```kotlin theme={"dark"}
enum class Status { ON, OFF }

val currentStatus = Status.ON
val statusMessage: String = when (currentStatus) {
    Status.ON -> "System is running"
    Status.OFF -> "System is halted"
    // No 'else' branch required because all enum constants are covered
}
```

**As a Statement:**
When used as a statement, the evaluated value is discarded. Historically, exhaustiveness was not required for statements. However, as of Kotlin 1.6, the compiler issues a warning, and as of Kotlin 1.7, it produces a hard compiler error if a `when` statement over an `enum`, `sealed` class, or `Boolean` is not exhaustive.

```kotlin theme={"dark"}
val numericValue = 1
when (numericValue) {
    1 -> println("One")
    2 -> println("Two")
    // else is optional here because 'numericValue' is an Int and the result is unassigned
}
```

## Branch Condition Syntax

Kotlin permits highly flexible branch conditions, moving beyond static constants. Multiple conditions can be combined on a single branch using a comma `,`, which acts as a logical `OR`.

**Constant and Arbitrary Expressions:**
Branches can match against literals, variables, or the evaluated result of a function call.

```kotlin theme={"dark"}
fun calculateValue(): Int = 5
val x = 5

when (x) {
    0, 1 -> print("x is 0 or 1")
    calculateValue() -> print("x matches the calculated value")
}
```

**Range and Collection Checks (`in` / `!in`):**
Branches can evaluate whether the subject exists within a specific `Iterable`, array, or `Range`.

```kotlin theme={"dark"}
val y = 15
val validNumbersArray = arrayOf(11, 12, 13)

when (y) {
    in 1..10 -> print("y is in the range")
    in validNumbersArray -> print("y is in the array")
    !in 10..20 -> print("y is outside the range")
}
```

**Type Checks and Smart Casting (`is` / `!is`):**
Branches can evaluate the runtime type of the subject. If an `is` check succeeds, the Kotlin compiler automatically smart-casts the subject to that type within the scope of the branch block.

```kotlin theme={"dark"}
val z: Any = "Kotlin"

when (z) {
    is String -> print(z.length) // z is smart-cast to String
    !is Int -> print("Not an integer")
}
```

## Subject-less `when`

The `when` keyword can be declared without a subject argument. In this configuration, it acts as a direct replacement for an `if-else if` chain. Every branch condition must evaluate to a `Boolean` expression.

```kotlin theme={"dark"}
val a = 5
val b = 4

when {
    a % 2 != 0 -> print("a is odd")
    b % 2 == 0 -> print("b is even")
    else -> print("Fallback")
}
```

## Variable Declaration in Subject

Kotlin allows the declaration of a variable directly within the subject parentheses of the `when` expression. The scope of this variable is strictly restricted to the body of the `when` block.

```kotlin theme={"dark"}
sealed class Response
class Success(val data: String) : Response()
class Failure(val error: String) : Response()

fun executeRequest(): Response = Success("Payload")

when (val response = executeRequest()) {
    is Success -> print(response.data) // 'response' is smart-cast to Success
    is Failure -> print(response.error) // 'response' is smart-cast to Failure
} // 'response' is inaccessible outside this block
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Kotlin Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
