Kotlin control flow
Core principle
Make the classified value obvious, keep branch-local predicates on their
branch, and let the compiler prove closed-domain coverage.
Procedure
Name the value being classified. If every branch tests it, use
when (subject); otherwise keep a subjectless when or if chain.
Choose the branch shape:
| Code shape |
Prefer |
| One classified value |
when (subject) |
| Unrelated boolean conditions |
Subjectless when or if/else |
| Primary case plus a branch-local predicate |
Guard condition |
| Invalid input before the main path |
Early return, require, or check |
| Closed value-returning domain |
Exhaustive when expression |
| Open input or deliberate fallback |
Explicit else |
Use a guard only on a subject when, after a primary condition, when the
extra predicate belongs to that branch and an unguarded branch still handles
the primary condition. Put the guarded branch first. Split comma-separated
conditions instead of guarding one of them. Guards are stable from Kotlin
2.2. Honor an explicit languageVersion setting; otherwise the project's
Kotlin version in its build file or version catalog is enough to confirm
support, so do not decline a guard for lack of further proof.
For a closed enum, Boolean, sealed type, or nullable closed type, name every
case and omit else. Match objects by value and class/data-class subtypes
with is. If the input is an open server/platform value or needs real
fallback/logging, keep else. Give each data-bearing subtype, including one
a catch-all collapses, its own is branch. When its data affects the
mapping or its safe handling, the finding or change must show the
smart-cast member access, even if the public value stays constant:
is Outcome.Failed -> safeFailureLabel(outcome.reason)
The is check smart-casts outcome, so the branch uses reason without a
cast; the helper name is illustrative. Naming cases alone, or sending callers
to inspect the original value, is not complete branch guidance. When the
data does not affect the result, keep the current value in that is branch;
do not invent a use of the data.
Use an early return only when it removes invalid or nullable state from the
main path. Keep nesting that expresses cleanup, transaction, or error
handling.
Verify smart casts still work without as, !!, mutable temporaries, or
duplicate casts. If they do not, keep the original shape or take a smaller
refactor.
Compile and test with the project's own build tool; in a Gradle project use
the Gradle run workflow, never raw Gradle. On failure, return to the smallest applicable earlier step
or retain the prior shape. Finish when the subject, fallbacks, and relevant
branch data are obvious to a reader and the resulting shape is easier to scan.
Recipes
Use guarded branches to refine one case, rather than nesting an if:
return when (event) {
is Event.Message if event.isUnread -> Row.Highlighted(event.message)
is Event.Message -> Row.Normal(event.message)
Event.Empty -> Row.Empty
}
Use a subject when when repeated conditions classify one value, and include
null as a branch when it is one case in a larger classification:
return when (val selected = selection) {
null -> SelectionUi.None
is Selection.Single if selected.item.isArchived -> SelectionUi.Archived(selected.item)
is Selection.Single -> SelectionUi.Active(selected.item)
is Selection.Multiple -> SelectionUi.Count(selected.items.size)
}
Do not introduce guards on unsupported Kotlin versions, force unrelated boolean
checks into a subject when, remove an open-world fallback, or flatten code
that obscures cleanup, transactions, or errors.
Related
1---2name: kotlin-control-flow3description: "Use when writing or reviewing Kotlin branching and control flow: when expressions, guard conditions, sealed type exhaustiveness, smart casts, nullable branching, early returns, or replacing complex if/else chains."4metadata:5 source: https://skillmd.com/skills/tuyv/kotlin-control-flow6---78# Kotlin control flow910## Core principle1112Make the classified value obvious, keep branch-local predicates on their13branch, and let the compiler prove closed-domain coverage.1415## Procedure16171. Name the value being classified. If every branch tests it, use18 `when (subject)`; otherwise keep a subjectless `when` or `if` chain.192. Choose the branch shape:2021 | Code shape | Prefer |22 |---|---|23 | One classified value | `when (subject)` |24 | Unrelated boolean conditions | Subjectless `when` or `if`/`else` |25 | Primary case plus a branch-local predicate | Guard condition |26 | Invalid input before the main path | Early return, `require`, or `check` |27 | Closed value-returning domain | Exhaustive `when` expression |28 | Open input or deliberate fallback | Explicit `else` |29303. Use a guard only on a subject `when`, after a primary condition, when the31 extra predicate belongs to that branch and an unguarded branch still handles32 the primary condition. Put the guarded branch first. Split comma-separated33 conditions instead of guarding one of them. Guards are stable from Kotlin34 2.2. Honor an explicit `languageVersion` setting; otherwise the project's35 Kotlin version in its build file or version catalog is enough to confirm36 support, so do not decline a guard for lack of further proof.374. For a closed enum, Boolean, sealed type, or nullable closed type, name every38 case and omit `else`. Match objects by value and class/data-class subtypes39 with `is`. If the input is an open server/platform value or needs real40 fallback/logging, keep `else`. Give each data-bearing subtype, including one41 a catch-all collapses, its own `is` branch. When its data affects the42 mapping or its safe handling, the finding or change must show the43 smart-cast member access, even if the public value stays constant:4445 ```kotlin46 is Outcome.Failed -> safeFailureLabel(outcome.reason)47 ```4849 The `is` check smart-casts `outcome`, so the branch uses `reason` without a50 cast; the helper name is illustrative. Naming cases alone, or sending callers51 to inspect the original value, is not complete branch guidance. When the52 data does not affect the result, keep the current value in that `is` branch;53 do not invent a use of the data.545. Use an early return only when it removes invalid or nullable state from the55 main path. Keep nesting that expresses cleanup, transaction, or error56 handling.576. Verify smart casts still work without `as`, `!!`, mutable temporaries, or58 duplicate casts. If they do not, keep the original shape or take a smaller59 refactor.607. Compile and test with the project's own build tool; in a Gradle project use61 the [Gradle run](../gradle-run/SKILL.md) workflow, never raw Gradle. On failure, return to the smallest applicable earlier step62 or retain the prior shape. Finish when the subject, fallbacks, and relevant63 branch data are obvious to a reader and the resulting shape is easier to scan.6465## Recipes6667Use guarded branches to refine one case, rather than nesting an `if`:6869```kotlin70return when (event) {71 is Event.Message if event.isUnread -> Row.Highlighted(event.message)72 is Event.Message -> Row.Normal(event.message)73 Event.Empty -> Row.Empty74}75```7677Use a subject `when` when repeated conditions classify one value, and include78`null` as a branch when it is one case in a larger classification:7980```kotlin81return when (val selected = selection) {82 null -> SelectionUi.None83 is Selection.Single if selected.item.isArchived -> SelectionUi.Archived(selected.item)84 is Selection.Single -> SelectionUi.Active(selected.item)85 is Selection.Multiple -> SelectionUi.Count(selected.items.size)86}87```8889Do not introduce guards on unsupported Kotlin versions, force unrelated boolean90checks into a subject `when`, remove an open-world fallback, or flatten code91that obscures cleanup, transactions, or errors.9293## Related9495- [Kotlin concurrency and Flow](../kotlin-concurrency-and-flow/SKILL.md) — state/event primitives.96- [Kotlin API design](../kotlin-api-design/SKILL.md) — explicit common-code branching.