Skip to main content
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.
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.
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.

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.
Range and Collection Checks (in / !in): Branches can evaluate whether the subject exists within a specific Iterable, array, or 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.

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.

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.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More