lang-kotlin
Use when the user asks about Kotlin 2.x, coroutines, Flow and StateFlow, structured concurrency, null safety, data/sealed/value classes, the K2 compiler, KSP…
от j4flmao★ 47 звёзд на GitHub
Установить lang-kotlin в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Kotlin
Purpose
Kotlin removes most null-pointer bugs at compile time and makes asynchronous code sequential-looking with coroutines. The common failures are leaking coroutines outside a scope, blocking threads inside suspend code, and fighting the type system with !!. This skill applies Kotlin 2.x idioms (K2 compiler) that avoid them.
Agent Protocol
Trigger
"Kotlin", "coroutines", "Flow", "StateFlow", "suspend", "structured concurrency", "null safety", "data class", "sealed interface", "extension function", "K2", "KSP", "Gradle Kotlin DSL", "MockK".
Input Context
- Kotlin and JVM target versions; platform (JVM server, Android, KMP shared module)
- Frameworks (Spring Boot, Ktor, Android Jetpack) and build tool (Gradle Kotlin DSL)
- Existing coroutine scopes/dispatchers and test setup
Output Artifact
Kotlin code, Gradle snippets, tests, or review findings. No file unless requested.
Response Format
Kotlin/JVM: {2.x / 17|21}
Change: {what and why}
Code: {snippet}
Concurrency: {scope, dispatcher, cancellation behaviour}
Verify: {./gradlew test, detekt/ktlint}
1. Null Safety
StringvsString?; smart casts after checks;?.,?:(Elvis),let,requireNotNull(x) { "message" }.!!throws NPE — acceptable only where an invariant is proven; prefer?: error("...")with context.- Java interop: Java types are platform types (
String!) — annotate Java code (@Nullable/@NonNull, JSpecify) or check at the boundary.
2. Modelling Data
@JvmInline value class OrderId(val value: String) // zero-cost wrapper on the JVM in most cases
data class Order(val id: OrderId, val total: Long, val status: Status)
sealed interface Status {
data object Pending : Status
data class Shipped(val trackingNo: String) : Status
data class Cancelled(val reason: String) : Status
}
fun describe(s: Status): String = when (s) { // exhaustive, no else needed
Status.Pending -> "pending"
is Status.Shipped -> "shipped: ${s.trackingNo}"
is Status.Cancelled -> "cancelled: ${s.reason}"
}
- Prefer
valand immutable collections (List,Map);copy()for updates. - Extension functions add behaviour without inheritance; they are resolved statically (no override).
- Scope functions:
apply(configure and return receiver),also(side effect),let(transform/null-check),run/with(compute with receiver) — keep chains short.
3. Coroutines and Structured Concurrency
- Every coroutine belongs to a
CoroutineScope; cancellation and failure propagate through the job hierarchy. Never useGlobalScopein application code. coroutineScope { }for parallel decomposition that fails together;supervisorScope { }when children fail independently.
suspend fun loadDashboard(userId: String): Dashboard = coroutineScope {
val profile = async { profileApi.get(userId) }
val orders = async { orderApi.recent(userId) }
Dashboard(profile.await(), orders.await()) // if one fails, the other is cancelled
}
- Dispatchers:
Default(CPU, cores-sized pool),IO(blocking I/O, elastic up to 64 threads by default),Main(UI). Wrap blocking calls inwithContext(Dispatchers.IO); never call blocking APIs onDefault/Main. - Cancellation is cooperative: suspension points check it; long CPU loops call
ensureActive(). Do not catchCancellationExceptionwithout rethrowing (bewarerunCatchingaround suspend calls). - Timeouts:
withTimeout(5.seconds) { ... }. - Shared mutable state: confine to one coroutine, use
Mutex(suspending) or atomics;synchronizedblocks must not suspend inside.
4. Flow
- Cold
Flowfor streams computed on collection;StateFlow(always has a value, conflated) for observable state;SharedFlowfor events. - Operators:
map,filter,debounce,distinctUntilChanged,flatMapLatest,combine,catch,flowOn(Dispatchers.IO)(changes the upstream context only). - Convert cold to hot with
stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial). - Collect lifecycle-aware on Android (
repeatOnLifecycle/collectAsStateWithLifecycle).
5. Collections and Sequences
Collection operators are eager (each step allocates a list); use asSequence() for long chains over large inputs or when short-circuiting (first { }). Use buildList { }, associateBy, groupBy, partition instead of manual loops where clearer.
6. Build and Tooling
- K2 compiler is the default since Kotlin 2.0; keep the Kotlin Gradle plugin, coroutines and serialization versions aligned (version catalog
libs.versions.toml). - Annotation processing: prefer KSP; kapt is in maintenance mode and slower.
kotlinx.serialization(@Serializable) for JSON without reflection; works across KMP targets.- Static analysis: detekt, ktlint (or the Kotlin compiler's own warnings as errors:
allWarningsAsErrors = true). - Java interop annotations:
@JvmStatic, `@JvmOverl
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/kotlin-advanced.md
- references/kotlin-fundamentals.md
- references/kotlin-testing.md
- references/reified-generics-dsl.md
FAQ
Что делает скилл lang-kotlin?
Use when the user asks about Kotlin 2.x, coroutines, Flow and StateFlow, structured concurrency, null safety, data/sealed/value classes, the K2 compiler, KSP, Gradle Kotlin DSL, MockK or kotlinx.serialization. Produces idiomatic JVM Kotlin and tests. Not for Android UI (use android) or KMP project structure (use mobile-kotlin-multiplatform).
Как установить скилл lang-kotlin?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл lang-kotlin запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…