К основному содержанию
скилл CX Codex

kotlin-control-flow — скилл для Claude Code: ветвления Kotlin

Скилл для ИИ-агента, который пишет и правит ветвления Kotlin: when, guard-условия, исчерпывающие проверки sealed-типов, smart casts.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add chrisbanes/skills --skill kotlin-control-flow -a claude-code
Открыть на GitHub

Что делает kotlin-control-flow

Скилл задаёт агенту процедуру работы с ветвлениями Kotlin. Сначала нужно назвать значение, которое классифицируется: если его проверяет каждая ветка, берётся when (subject), иначе остаётся when без субъекта или цепочка if. Дальше идёт таблица выбора формы ветки — от одного классифицируемого значения до закрытого домена с возвратом значения.

Guard-условия применяются только на when с субъектом, после основной проверки, и ставятся перед ней. Они стабильны начиная с Kotlin 2.2. Если в проекте явно задан languageVersion, ориентируйтесь на него; иначе достаточно версии Kotlin в build-файле или version catalog — отказываться от guard из-за нехватки доказательств не нужно. Для закрытого enum, Boolean, sealed-типа или nullable-закрытого типа перечисляются все случаи, а else опускается. Открытые значения сервера или платформы, которым нужен реальный fallback, наоборот, оставляют else.

Smart casts проверяются без as, !!, изменяемых временных переменных и повторных приведений. Если так не выходит, форма остаётся прежней или рефакторинг берётся меньше. Компиляция и тесты идут через build-инструмент проекта: в Gradle-проекте — по workflow gradle-run, а не сырым Gradle. При падении агент возвращается к самому раннему подходящему шагу.

Какие задачи решает

  • заменить длинную цепочку if/else на when с субъектом
  • добавить guard-условие к одной ветке вместо вложенного if
  • проверить исчерпывающее покрытие sealed-типа без else
  • убрать лишние as и !! там, где работает smart cast
  • вынести проверку невалидного входа в early return или require

Примеры запросов агенту

  • Перепиши этот when на guard-условия, где предикат относится к конкретной ветке
  • Проверь, что when по sealed-типу покрывает все случаи и не нуждается в else
  • Убери !! и повторные приведения в этом разборе Selection

Как установить kotlin-control-flow

1Через Skills CLI (Vercel)

npx skills add chrisbanes/skills --skill kotlin-control-flow -a claude-code

2Вручную: положить файлы

~/.claude/skills/kotlin-control-flow/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/kotlin-control-flow/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о kotlin-control-flow

Как установить kotlin-control-flow в Claude?

Выполните npx skills add chrisbanes/skills --skill kotlin-control-flow -a claude-code. Скилл появится в ~/.claude/skills/kotlin-control-flow/SKILL.md.

Что делает kotlin-control-flow?

Подсказывает агенту, как выбирать форму ветвления в Kotlin: when с субъектом или без, guard-условия, early return, исчерпывающие when-выражения. Работает при написании и ревью кода.

С какой версии Kotlin доступны guard-условия?

Guard-условия стабильны с Kotlin 2.2. Если в проекте задан languageVersion, проверяйте по нему, иначе хватит версии Kotlin в build-файле или version catalog.

Исходный текст

SKILL.md · Apache-2.0
---
name: kotlin-control-flow
description: "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."
---

# 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

1. Name the value being classified. If every branch tests it, use
   `when (subject)`; otherwise keep a subjectless `when` or `if` chain.
2. 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` |

3. 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.
4. 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:

   ```kotlin
   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.
5. 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.
6. 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.
7. Compile and test with the project's own build tool; in a Gradle project use
   the [Gradle run](../gradle-run/SKILL.md) 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`:

```kotlin
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:

```kotlin
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

- [Kotlin concurrency and Flow](../kotlin-concurrency-and-flow/SKILL.md) — state/event primitives.
- [Kotlin API design](../kotlin-api-design/SKILL.md) — explicit common-code branching.

© chrisbanes · Apache-2.0 · chrisbanes/skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →
go-control-flow cxuu Скилл учит агента писать канонические циклы, ветвления и switch в Go. Пригодится при оформлении guard clauses и предотвращении багов с затенением переменных. CX Codex +1 1 200установок kotlin-patterns affaan-m Скилл задаёт правила идиоматичного Kotlin для ИИ-агентов. Пригодится при ревью кода, настройке корутин и избавлении от лишних проверок на null. CX Codex +1 4 800установок kotlin-springboot официальный github Скилл задаёт практики Spring Boot и Kotlin: от структуры проекта до тестов и корутин. Подходит, когда агент пишет или проверяет серверное приложение. 9 781установок kotlin-mcp-server-generator официальный github Скилл создаёт Kotlin-проект MCP-сервера с Gradle, официальным SDK и базовыми инструментами. Пригодится, когда нужен готовый каркас нового сервера. 8 700установок kotlin-specialist https://github.com/Jeffallan Скилл направляет ИИ при разработке на Kotlin: корутины, Flow, KMP, Compose и Ktor. Пригодится для реализации функций с проверками стиля и отмены задач. CX Codex +1 5 200установок kotlin-coroutines-flows affaan-m Скилл подсказывает паттерны Kotlin Coroutines и Flow для Android и KMP. Пригодится при отладке отмены, параллельных задач и тестов. CX Codex +1 4 800установок

Из того же набора17

kotlin-concurrency-and-flow Скилл для ревью и написания Kotlin-кода с корутинами: разбирает владение scope, отмену, StateFlow, SharedFlow и Channel. CX Codex +1 1 100установок compose-performance Скилл для расследования стоимости рекомпозиции в Jetpack Compose: помогает найти фазу, из-за которой пересчитывается UI, и починить её точечно. CX Codex +1 1 100установок compose-state-and-effects Скилл помогает проектировать и проверять владение состоянием в Jetpack Compose. Он распределяет стейт по уровням и подбирает эффекты под их жизненный цикл. CX Codex +1 1 100установок using-chrisbanes-skills Разбирает задачу по Kotlin или Jetpack Compose и подключает нужный скилл из набора chrisbanes. Полезен, когда в одном изменении пересекаются несколько тем. CX Codex +1 1 100установок compose-component-design Скилл для проектирования и ревью переиспользуемых компонентов Jetpack Compose: слоты, модификаторы, размещение корневого layout. CX Codex +1 1 000установок kotlin-api-design Помогает решить, кому принадлежит функция, где ставить extension, а где хватит value class. Пригодится при проектировании публичного API на Kotlin и в KMP. CX Codex +1 949установок gradle-run Скилл гоняет сборки Gradle через обёртку с компактным выводом и ведёт журнал запусков, чтобы агент не заливал контекст полным логом. CX Codex +1 768установок run-github-project Ведёт работу по колонкам GitHub Project: разбирает Todo, берёт задачи в Ready to implement и доводит до Done. CX Codex +1 643установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой