TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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.
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.
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.
in / !in):
Branches can evaluate whether the subject exists within a specific Iterable, array, or Range.
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 thewhen expression. The scope of this variable is strictly restricted to the body of the when block.
Master Kotlin with Deep Grasping Methodology!Learn More





