kotlin
БесплатноБез исполняемых скриптовНе проверенKotlin language fundamentals. Covers null safety, coroutines, flow, sealed classes, data classes, scope functions, and Kotlin 2.x features (K2 compiler…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Kotlin Core Knowledge
Reference: coroutines.md for structured concurrency, Flow, channels. advanced.md for sealed hierarchies, generics variance, context parameters, KSP.
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:kotlin.
Null Safety
var name: String = "Alice" // Non-nullable
var maybe: String? = null // Nullable
val len = maybe?.length ?: 0 // Safe call + Elvis
val forced = maybe!!.length // Throws NPE if null — avoid
// Smart casts
fun describe(x: Any?): String = when (x) {
is String -> "String of length ${x.length}" // smart-cast to String
null -> "null"
else -> x.toString()
}
Data Classes
data class User(
val id: Long,
val name: String,
val email: String,
val active: Boolean = true,
)
val u = User(1, "Alice", "[email protected]")
val updated = u.copy(active = false)
val (id, name) = u // destructuring
Auto-generates equals, hashCode, toString, copy, componentN. Avoid for entities with identity (use regular class).
Sealed Classes & When
sealed interface Result<out T> {
data class Success<T>(val value: T) : Result<T>
data class Error(val cause: Throwable) : Result<Nothing>
data object Loading : Result<Nothing>
}
fun <T> handle(r: Result<T>): String = when (r) {
is Result.Success -> "ok: ${r.value}"
is Result.Error -> "error: ${r.cause.message}"
Result.Loading -> "loading"
// exhaustive — no else needed
}
sealed confines hierarchy to same module/package. Prefer sealed interface over sealed class when no shared state.
Scope Functions — When to Use Which
| Function | Receiver | Returns | Use case |
|---|---|---|---|
let |
it |
block result | Null-safe transform: user?.let { send(it) } |
run |
this |
block result | Compute on object: config.run { host + port } |
apply |
this |
receiver | Builder-style init: Intent().apply { setAction(...) } |
also |
it |
receiver | Side effect (log): result.also { log(it) } |
with |
this |
block result | Group calls on object (not chained) |
val view = TextView(context).apply {
text = "Hello"
textSize = 16f
}.also { log("created: $it") }
Coroutines — Essentials
import kotlinx.coroutines.*
suspend fun fetchUser(id: Long): User {
delay(100) // suspend, doesn't block thread
return User(id, "...", "...")
}
fun main() = runBlocking {
val user = async { fetchUser(1) }
val posts = async { fetchPosts(1) }
println("${user.await()} -> ${posts.await()}")
}
Rules:
suspendfunctions can only be called from coroutine or anothersuspend- Use
withContext(Dispatchers.IO)for blocking I/O - Use
coroutineScope { }for parent-child cancellation propagation - Never use
GlobalScopein production
See coroutines.md for structured concurrency, Flow, channels, exception handling.
Flow (Cold Streams)
fun ticker(): Flow<Int> = flow {
var i = 0
while (true) {
emit(i++)
delay(1000)
}
}
// Collect
viewModelScope.launch {
ticker()
.map { it * 2 }
.filter { it % 4 == 0 }
.collect { println(it) }
}
StateFlow (hot, single-value) for UI state. SharedFlow for one-shot events.
Extension Functions
fun String.toSlug(): String =
this.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
"Hello World!".toSlug() // "hello-world"
Resolved statically. Don't override; can't access private members of receiver.
Generics & Variance
class Box<out T>(val value: T) // covariant: Box<Cat> is Box<Animal>
class Sink<in T> { fun put(v: T) {} } // contravariant: Sink<Animal> is Sink<Cat>
inline fun <reified T> isType(x: Any) = x is T // reified: T available at runtime
Idiomatic Patterns
// Single-expression functions
fun double(x: Int) = x * 2
// Default + named args (replace builders)
fun connect(host: String, port: Int = 80, secure: Boolean = false) {}
connect(host = "localhost", secure = true)
// Destructuring maps
for ((key, value) in map) { /* ... */ }
// require / check / error for preconditions
fun divide(a: Int, b: Int): Int {
require(b != 0) { "b must be non-zero" }
return a / b
}
Anti-Patterns
| Anti-pattern | Why it's bad | Correct approach |
|---|---|---|
!! everywhere |
NPE risk | Safe call ?. + Elvis ?: |
runBlocking in suspend chain |
Blocks thread | Compose with coroutineScope |
GlobalScope.launch |
No cancellation | Use bound scope (viewModelScope, lifecycleScope) |
lateinit on nullable types |
Compile error | Use var x: T? = null |
Catching Throwable in coroutine |
Hides cancellation | Catch Exception, rethrow CancellationException |
Mutable var shared across coroutines |
Race conditions |
Установить kotlin в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл kotlin?
Kotlin language fundamentals. Covers null safety, coroutines, flow, sealed classes, data classes, scope functions, and Kotlin 2.x features (K2 compiler, context parameters). Use for Kotlin/JVM, Kotlin/Native, Kotlin/JS work. USE WHEN: user mentions "Kotlin", "coroutines", "suspend", "Flow", "sealed class", "data class", "scope functions", "K2 compiler", "ksp", "Kotlin 2.x" DO NOT USE FOR: reviewing existing Kotlin code - use `review/kotlin`, which covers the Java boundary and the concurrency the compiler does not check DO NOT USE FOR: Kotlin Multiplatform setup - use `mobile/kotlin-multiplatform` DO NOT USE FOR: Compose UI - use `frontend-frameworks/compose-multiplatform` DO NOT USE FOR: Spring Boot Kotlin - use `spring-boot` framework skill
Как установить скилл kotlin?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл kotlin запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create 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…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic