Kotlin

Kotlin / Android.

Kotlin / Android. Coroutine structure and lifetime dominate — GlobalScope launches that outlive their owner, blocking calls inside suspend functions, broad catches that also swallow CancellationException and break structured cancellation, mutable state shared across coroutines without confinement. The rest is Android-specific state discipline: Activity Context leaked by a singleton, mutable StateFlow/LiveData exposed publicly instead of read-only, force-unwrap (!!) in production paths.

Which repositories get it

A repository on this profile: mobile-android. redline init detects the profile and --profile overrides it — see Profiles & stacks.

Within such a repository, a file gets these rules when it matches one of these globs:

  • **/*.kt
  • **/*.kts

The 25 rules

When a review comment cites one of these ids, this is where to look up what it catches. Of the 25, 8 BLOCKER, 14 HIGH and 3 SUGGESTION. A finding from this file opens like this:

a finding from this file
Redline/BLOCKER [kotlin/force-unwrap]: <one-line problem>

What each severity obliges you to do is on The output contract.

Rule idSeverityCatches
kotlin/force-unwrapBLOCKER`!!` non-null assertions in production paths — restructure with `?.`, `?:`, `requireNotNull` with a message, or fix the type.
kotlin/globalscopeBLOCKER`GlobalScope.launch` — coroutines must live in a structured scope (`viewModelScope`, `lifecycleScope`, injected `CoroutineScope`); GlobalScope leaks work past the owner's lifetime.
kotlin/blocking-in-coroutineBLOCKERBlocking inside coroutines: `Thread.sleep`, blocking IO, or `runBlocking` on `Dispatchers.Main` / inside `suspend` functions — use `delay`, suspending clients, or `withContext(Dispatchers.IO)`.
kotlin/context-leakBLOCKERAndroid `Context` held by singletons / companion objects — activity context leaks the whole view tree; application context only, and only when unavoidable.
kotlin/broad-catch-cancellationBLOCKERCatching `Exception`/`Throwable` broadly and continuing — also swallows `CancellationException`, breaking coroutine cancellation; catch specific types and rethrow `CancellationException`.
kotlin/unconfined-shared-stateBLOCKERMutable shared state across coroutines without confinement — use `Mutex`, `StateFlow`, or single-thread confinement.
kotlin/lateinit-misuseBLOCKER`lateinit` used to dodge nullability logic — acceptable only for framework-injected fields (DI, Android lifecycle).
kotlin/todo-stubBLOCKER`TODO()` / `throw NotImplementedError()` in production code. The IDE's placeholder compiles and ships, and `NotImplementedError` is an `Error`, so `catch (e: Exception)` does not stop it — the first refund request crashes the app or the request thread. Implement it, or throw `UnsupportedOperationException("why")` for a deliberately unsupported operation. Not in test fakes.
kotlin/public-mutable-stateHIGHPublic `MutableStateFlow` / `MutableLiveData` — expose read-only `StateFlow`/`LiveData`, mutate privately.
kotlin/lifecycle-unaware-collectionHIGHFlow collection in UI without `repeatOnLifecycle` / `collectAsStateWithLifecycle` — collects while backgrounded.
kotlin/hardcoded-dispatcherHIGHHardcoded `Dispatchers.*` in classes — inject dispatchers for testability.
kotlin/data-class-varHIGH`data class` with `var` properties — copy/equality semantics break; use `val` + `copy`.
kotlin/companion-mutable-stateHIGHCompanion-object mutable state (global by another name).
kotlin/runcatching-silent-defaultHIGH`runCatching` chains that map failure to a default silently.
kotlin/force-unwrap-in-testsHIGH`!!` in tests hiding what the test actually asserts — use `assertNotNull` semantics.
kotlin/dropped-exception-causeHIGHA new exception thrown with only `e.message`. `throw RepositoryException(e.message)` loses the original type and trace, so a certificate-expiry outage is diagnosed as an app bug. Pass the cause: `throw RepositoryException("context", e)`.
kotlin/downcast-readonly-collectionHIGHA read-only `List`/`Set`/`Map` cast to `Mutable*` to mutate it. It throws `UnsupportedOperationException` on `listOf`/`emptyList`, or silently mutates a collection the caller thinks is immutable — mutating a `StateFlow` value in place so `distinctUntilChanged` never emits. Copy with `toMutableList()`, or expose a mutable type honestly.
kotlin/else-on-exhaustive-whenHIGHAn `else ->` branch in a `when` over a sealed type, enum or Boolean. It switches off the compiler's exhaustiveness check, so a variant added later silently takes the default — `Refunded` landing in `else -> showSuccess()`. List every case and let the build fail on new ones.
kotlin/suspend-in-finallyHIGHSuspending cleanup in `finally` without `withContext(NonCancellable)`. On cancellation the first suspension point in `finally` throws immediately, so the cleanup never runs and the server-side lock or upload session leaks. Wrap it: `finally { withContext(NonCancellable) { release() } }`.
kotlin/launch-in-test-without-runtestHIGH`launch`/`async` in a `@Test` outside `runTest`. The test returns before the coroutine runs, so its assertions never execute or fail an unrelated later test. Wrap the body in `runTest { }` and use the test dispatcher.
kotlin/implicit-default-localeHIGH`String.format` / `"…".format()` / `uppercase()`-style calls producing machine-read text without an explicit `Locale`. On a German device `"%.2f".format(amount)` sends `12,50` and the payment API rejects it. Pass `Locale.ROOT` for anything parsed, signed, hashed or sent. Not for display text.
kotlin/print-stack-traceHIGH`e.printStackTrace()` in a catch. It goes to stderr or logcat, past the logger and crash reporting, so a production-wide failure never reaches Crashlytics. Log it with context through the logger or crash reporter, then rethrow or surface the failure.
kotlin/prefer-sealed-stateSUGGESTIONSealed interfaces/classes for UI and result states instead of nullable-field combinations.
kotlin/value-class-identifiersSUGGESTION`value class` for domain identifiers (MSISDN, AccountId) instead of raw `String`.
kotlin/deep-scope-function-nestingSUGGESTIONNested `let`/`apply`/`run` chains more than two deep — extract a function.

Changing a rule

Edit standards/stacks/kotlin.md and nowhere else. Every other copy is generated from it. A merged change reaches every onboarded repository as a pull request, so treat it as a production change.

Rule ids are permanent. Reword a rule freely; it keeps its id. Renaming or removing an id orphans every telemetry record that cited it.

  1. Edit the markdownstandards/ is the only place a human edits a rule. AGENTS.md, CLAUDE.md, .github/copilot-instructions.md and .github/instructions/ are rendered from it, and the next render overwrites any hand edit there.
  2. node scripts/assign-rule-ids.mjsAssigns a permanent <stack>/<slug> id to any new rule bullet and rewrites the file in place. Do not invent an id by hand. CI runs the same script with --check and fails if a rule is missing one.
  3. node scripts/render-self.mjsRe-renders this repository's own copies of those files. CI runs it with --check, so a stale copy fails the build.
  4. Bump standards/manifest.json → versionIn the same pull request as the rule change. Sync pull requests quote the version, so every repository can tell which standards it is on.
  5. Add a CHANGELOG.md entryAlso in the same pull request. Say what changed and why, and record the seed score: a standards change with no measurement is an opinion.
  6. node scripts/validate.mjsThe self-check CI runs: the manifest is consistent, rule ids are well formed, the output contract is intact, and every glob is one Copilot can read.

The full file

standards/stacks/kotlin.md · 55 lines · 5.2 KB
# Kotlin Review Rules (Android + backend)

## BLOCKER — request changes

- `kotlin/force-unwrap` — **`!!` non-null assertions** in production paths — restructure with `?.`, `?:`, `requireNotNull` with a message, or fix the type.
- `kotlin/globalscope` — **`GlobalScope.launch`** — coroutines must live in a structured scope (`viewModelScope`, `lifecycleScope`, injected `CoroutineScope`); GlobalScope leaks work past the owner's lifetime.
- `kotlin/blocking-in-coroutine` — **Blocking inside coroutines**: `Thread.sleep`, blocking IO, or `runBlocking` on `Dispatchers.Main` / inside `suspend` functions — use `delay`, suspending clients, or `withContext(Dispatchers.IO)`.
- `kotlin/context-leak` — **Android `Context` held by singletons / companion objects** — activity context leaks the whole view tree; application context only, and only when unavoidable.
- `kotlin/broad-catch-cancellation` — **Catching `Exception`/`Throwable` broadly and continuing** — also swallows `CancellationException`, breaking coroutine cancellation; catch specific types and rethrow `CancellationException`.
- `kotlin/unconfined-shared-state` — **Mutable shared state across coroutines without confinement** — use `Mutex`, `StateFlow`, or single-thread confinement.
- `kotlin/lateinit-misuse` — **`lateinit` used to dodge nullability logic** — acceptable only for framework-injected fields (DI, Android lifecycle).
- `kotlin/todo-stub` — **`TODO()` / `throw NotImplementedError()` in production code.** The IDE's placeholder
  compiles and ships, and `NotImplementedError` is an `Error`, so `catch (e: Exception)` does not stop it — the
  first refund request crashes the app or the request thread. Implement it, or throw
  `UnsupportedOperationException("why")` for a deliberately unsupported operation. Not in test fakes.

## HIGH

- `kotlin/public-mutable-state` — Public `MutableStateFlow` / `MutableLiveData` — expose read-only `StateFlow`/`LiveData`, mutate privately.
- `kotlin/lifecycle-unaware-collection` — Flow collection in UI without `repeatOnLifecycle` / `collectAsStateWithLifecycle` — collects while backgrounded.
- `kotlin/hardcoded-dispatcher` — Hardcoded `Dispatchers.*` in classes — inject dispatchers for testability.
- `kotlin/data-class-var` — `data class` with `var` properties — copy/equality semantics break; use `val` + `copy`.
- `kotlin/companion-mutable-state` — Companion-object mutable state (global by another name).
- `kotlin/runcatching-silent-default` — `runCatching` chains that map failure to a default silently.
- `kotlin/force-unwrap-in-tests` — `!!` in tests hiding what the test actually asserts — use `assertNotNull` semantics.
- `kotlin/dropped-exception-cause` — **A new exception thrown with only `e.message`.** `throw
  RepositoryException(e.message)` loses the original type and trace, so a certificate-expiry outage is diagnosed
  as an app bug. Pass the cause: `throw RepositoryException("context", e)`.
- `kotlin/downcast-readonly-collection` — **A read-only `List`/`Set`/`Map` cast to `Mutable*` to mutate it.** It
  throws `UnsupportedOperationException` on `listOf`/`emptyList`, or silently mutates a collection the caller
  thinks is immutable — mutating a `StateFlow` value in place so `distinctUntilChanged` never emits. Copy with
  `toMutableList()`, or expose a mutable type honestly.
- `kotlin/else-on-exhaustive-when` — **An `else ->` branch in a `when` over a sealed type, enum or Boolean.** It
  switches off the compiler's exhaustiveness check, so a variant added later silently takes the default —
  `Refunded` landing in `else -> showSuccess()`. List every case and let the build fail on new ones.
- `kotlin/suspend-in-finally` — **Suspending cleanup in `finally` without `withContext(NonCancellable)`.** On
  cancellation the first suspension point in `finally` throws immediately, so the cleanup never runs and the
  server-side lock or upload session leaks. Wrap it: `finally { withContext(NonCancellable) { release() } }`.
- `kotlin/launch-in-test-without-runtest` — **`launch`/`async` in a `@Test` outside `runTest`.** The test
  returns before the coroutine runs, so its assertions never execute or fail an unrelated later test. Wrap the
  body in `runTest { }` and use the test dispatcher.
- `kotlin/implicit-default-locale` — **`String.format` / `"…".format()` / `uppercase()`-style calls producing
  machine-read text without an explicit `Locale`.** On a German device `"%.2f".format(amount)` sends `12,50` and
  the payment API rejects it. Pass `Locale.ROOT` for anything parsed, signed, hashed or sent. Not for display
  text.
- `kotlin/print-stack-trace` — **`e.printStackTrace()` in a catch.** It goes to stderr or logcat, past the
  logger and crash reporting, so a production-wide failure never reaches Crashlytics. Log it with context
  through the logger or crash reporter, then rethrow or surface the failure.

## SUGGESTION

- `kotlin/prefer-sealed-state` — Sealed interfaces/classes for UI and result states instead of nullable-field combinations.
- `kotlin/value-class-identifiers` — `value class` for domain identifiers (MSISDN, AccountId) instead of raw `String`.
- `kotlin/deep-scope-function-nesting` — Nested `let`/`apply`/`run` chains more than two deep — extract a function.