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 expression in Kotlin evaluates a target argument against multiple branch conditions. By combining when with the in or !in operators, a branch can evaluate whether the target argument exists within a ClosedRange, OpenEndRange, Progression, Collection, Array, or any custom type that implements the contains operator function.
Syntax Mechanics
To evaluate a range or collection within awhen block, the branch condition must be prefixed with the in (contains) or !in (does not contain) operator, followed by the range or collection definition. The arrow -> must be followed by a valid expression, statement, or block.
Under the Hood
- Operator Delegation: The
inkeyword in awhenbranch is syntactic sugar for thecontains()operator function. For example,in a..btranslates to(a..b).contains(target), andin collectiontranslates tocollection.contains(target). - Primitive Optimization: For primitive types (
Int,Long,Char), the Kotlin compiler optimizes theinrange check. Instead of allocating a range object and invokingcontains(), it compiles directly to highly efficient boolean comparison logic (e.g.,start <= target && target <= end). - Sequential Evaluation:
whenbranches are evaluated top-to-bottom. The expression short-circuits and executes the first branch where theincondition evaluates totrue.
Supported Types for in Checks
The when check using in is not limited to numeric primitives. It supports any type that forms a valid range or provides a containment check mechanism.
- Standard Progressions:
IntRange,LongRange, andCharRange. - Collections and Arrays: Any
Iterable,Collection(such asListorSet), orArray. - Custom Comparables: Any class implementing
Comparable<T>can be used with the..operator to create aClosedRange. - Custom Contains: Any arbitrary type that defines an
operator fun contains(value: T): Boolean.
Exhaustiveness Requirements
Since Kotlin 1.7, exhaustiveness is strictly enforced forwhen statements if the subject is an enum, sealed class/interface, or Boolean.
However, for types typically evaluated with ranges or collections (such as Int, Long, or String), the compiler cannot statically verify that a set of ranges covers the entire domain of the type (e.g., all 32 bits of an Int). Because of this limitation, an else branch is strictly required whenever a when block containing ranges is used as an expression (where it returns a value to a variable). When used as a statement with non-exhaustive types like Int or String, the else branch remains optional.
Master Kotlin with Deep Grasping Methodology!Learn More





