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.
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; retain the smart-cast payload when the mapping needs it. If the
input is an open server/platform value or needs real fallback/logging, keep
else.
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. On failure, return to the smallest applicable earlier step
or retain the prior shape. Finish when the subject, fallbacks, and 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-flow
3description: "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/chrisbanes/kotlin-control-flow
6---
7
8# Kotlin control flow
9
10## Core principle
11
12Make the classified value obvious, keep branch-local predicates on their
13branch, and let the compiler prove closed-domain coverage.
14
15## Procedure
16
171. Name the value being classified. If every branch tests it, use
18 `when (subject)`; otherwise keep a subjectless `when` or `if` chain.
192. Choose the branch shape:
20
21 | 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` |
29
303. Use a guard only on a subject `when`, after a primary condition, when the
31 extra predicate belongs to that branch and an unguarded branch still handles
32 the primary condition. Put the guarded branch first. Split comma-separated
33 conditions instead of guarding one of them.
344. For a closed enum, Boolean, sealed type, or nullable closed type, name every
35 case and omit `else`. Match objects by value and class/data-class subtypes
36 with `is`; retain the smart-cast payload when the mapping needs it. If the
37 input is an open server/platform value or needs real fallback/logging, keep
38 `else`.
395. Use an early return only when it removes invalid or nullable state from the
40 main path. Keep nesting that expresses cleanup, transaction, or error
41 handling.
426. Verify smart casts still work without `as`, `!!`, mutable temporaries, or
43 duplicate casts. If they do not, keep the original shape or take a smaller
44 refactor.
457. Compile and test. On failure, return to the smallest applicable earlier step
46 or retain the prior shape. Finish when the subject, fallbacks, and branch
47 data are obvious to a reader and the resulting shape is easier to scan.
48
49## Recipes
50
51Use guarded branches to refine one case, rather than nesting an `if`:
52
53```kotlin
54return when (event) {
55 is Event.Message if event.isUnread -> Row.Highlighted(event.message)
56 is Event.Message -> Row.Normal(event.message)
57 Event.Empty -> Row.Empty
58}
59```
60
61Use a subject `when` when repeated conditions classify one value, and include
62`null` as a branch when it is one case in a larger classification:
63
64```kotlin
65return when (val selected = selection) {
66 null -> SelectionUi.None
67 is Selection.Single if selected.item.isArchived -> SelectionUi.Archived(selected.item)
68 is Selection.Single -> SelectionUi.Active(selected.item)
69 is Selection.Multiple -> SelectionUi.Count(selected.items.size)
70}
71```
72
73Do not introduce guards on unsupported Kotlin versions, force unrelated boolean
74checks into a subject `when`, remove an open-world fallback, or flatten code
75that obscures cleanup, transactions, or errors.
76
77## Related
78
79- [Kotlin concurrency and Flow](../kotlin-concurrency-and-flow/SKILL.md) — state/event primitives.
80- [Kotlin API design](../kotlin-api-design/SKILL.md) — explicit common-code branching.