[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AKB56JNR01WM5B0724E30A":3,"skill-same:01M7AKB56JNR01WM5B0724E30A":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AKB56JNR01WM5B0724E30A","kotlin-patterns",null,"コルーチン、null 安全性、DSL ビルダーを使用して堅牢・効率的・保守性の高い Kotlin アプリケーションを構築するための慣用的な Kotlin パターン、ベストプラクティス、規約。","Cyrilthetecchieee\u002Fcyril-code-","Cyrilthetecchieee","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219787998?v=4","01M7AF0MMMKRAA0H61XMJPV92H","Julian Cyril D ","01M7AF0MQ10AVG6QJQ1C2BC0F5",2,"MIT","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fkotlin-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: kotlin-patterns\ndescription: コルーチン、null 安全性、DSL ビルダーを使用して堅牢・効率的・保守性の高い Kotlin アプリケーションを構築するための慣用的な Kotlin パターン、ベストプラクティス、規約。\norigin: ECC\n---\n\n# Kotlin 開発パターン\n\n堅牢・効率的・保守性の高いアプリケーションを構築するための慣用的な Kotlin パターンとベストプラクティス。\n\n## 使用するタイミング\n\n- 新しい Kotlin コードを書く\n- Kotlin コードをレビューする\n- 既存の Kotlin コードをリファクタリングする\n- Kotlin モジュールまたはライブラリを設計する\n- Gradle Kotlin DSL ビルドを設定する\n\n## 動作の仕組み\n\nこのスキルは 7 つの主要領域にわたって慣用的な Kotlin の規約を適用します: 型システムとセーフコール演算子を使用した null 安全性、`val` とデータクラスの `copy()` によるイミュータビリティ、網羅的な型階層のためのシールドクラスとインターフェース、コルーチンと `Flow` による構造化並行性、継承なしで振る舞いを追加する拡張関数、`@DslMarker` とラムダレシーバーを使用した型安全 DSL ビルダー、そしてビルド設定のための Gradle Kotlin DSL。\n\n## 使用例\n\n**Elvis 演算子を使用した null 安全性:**\n```kotlin\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n```\n\n**網羅的な結果のためのシールドクラス:**\n```kotlin\nsealed class Result\u003Cout T> {\n    data class Success\u003CT>(val data: T) : Result\u003CT>()\n    data class Failure(val error: AppError) : Result\u003CNothing>()\n    data object Loading : Result\u003CNothing>()\n}\n```\n\n**async\u002Fawait を使用した構造化並行性:**\n```kotlin\nsuspend fun fetchUserWithPosts(userId: String): UserProfile =\n    coroutineScope {\n        val user = async { userService.getUser(userId) }\n        val posts = async { postService.getUserPosts(userId) }\n        UserProfile(user = user.await(), posts = posts.await())\n    }\n```\n\n## コア原則\n\n### 1. Null 安全性\n\nKotlin の型システムは null 可能型と非 null 型を区別します。これを最大限に活用してください。\n\n```kotlin\n\u002F\u002F 良い例: デフォルトで非 null 型を使用\nfun getUser(id: String): User {\n    return userRepository.findById(id)\n        ?: throw UserNotFoundException(\"User $id not found\")\n}\n\n\u002F\u002F 良い例: セーフコールと Elvis 演算子\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n\n\u002F\u002F 悪い例: null 可能型を強制アンラップ\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user!!.email \u002F\u002F null の場合 NPE をスロー\n}\n```\n\n### 2. デフォルトでイミュータブル\n\n`var` より `val` を優先し、ミュータブルコレクションよりイミュータブルコレクションを優先してください。\n\n```kotlin\n\u002F\u002F 良い例: イミュータブルデータ\ndata class User(\n    val id: String,\n    val name: String,\n    val email: String,\n)\n\n\u002F\u002F 良い例: copy() で変換\nfun updateEmail(user: User, newEmail: String): User =\n    user.copy(email = newEmail)\n\n\u002F\u002F 良い例: イミュータブルコレクション\nval users: List\u003CUser> = listOf(user1, user2)\nval filtered = users.filter { it.email.isNotBlank() }\n\n\u002F\u002F 悪い例: ミュータブルな状態\nvar currentUser: User? = null \u002F\u002F ミュータブルなグローバル状態を避ける\nval mutableUsers = mutableListOf\u003CUser>() \u002F\u002F 本当に必要な場合のみ使用\n```\n\n### 3. 式ボディと単一式関数\n\n簡潔で読みやすい関数には式ボディを使用してください。\n\n```kotlin\n\u002F\u002F 良い例: 式ボディ\nfun isAdult(age: Int): Boolean = age >= 18\n\nfun formatFullName(first: String, last: String): String =\n    \"$first $last\".trim()\n\nfun User.displayName(): String =\n    name.ifBlank { email.substringBefore('@') }\n\n\u002F\u002F 良い例: 式としての when\nfun statusMessage(code: Int): String = when (code) {\n    200 -> \"OK\"\n    404 -> \"Not Found\"\n    500 -> \"Internal Server Error\"\n    else -> \"Unknown status: $code\"\n}\n\n\u002F\u002F 悪い例: 不要なブロックボディ\nfun isAdult(age: Int): Boolean {\n    return age >= 18\n}\n```\n\n### 4. 値オブジェクトのためのデータクラス\n\n主にデータを保持する型にはデータクラスを使用してください。\n\n```kotlin\n\u002F\u002F 良い例: copy、equals、hashCode、toString を持つデータクラス\ndata class CreateUserRequest(\n    val name: String,\n    val email: String,\n    val role: Role = Role.USER,\n)\n\n\u002F\u002F 良い例: 型安全性のための値クラス（ランタイムでゼロオーバーヘッド）\n@JvmInline\nvalue class UserId(val value: String) {\n    init {\n        require(value.isNotBlank()) { \"UserId cannot be blank\" }\n    }\n}\n\n@JvmInline\nvalue class Email(val value: String) {\n    init {\n        require('@' in value) { \"Invalid email: $value\" }\n    }\n}\n\nfun getUser(id: UserId): User = userRepository.findById(id)\n```\n\n## シールドクラスとインターフェース\n\n### 制限された階層のモデリング\n\n```kotlin\n\u002F\u002F 良い例: 網羅的な when のためのシールドクラス\nsealed class Result\u003Cout T> {\n    data class Success\u003CT>(val data: T) : Result\u003CT>()\n    data class Failure(val error: AppError) : Result\u003CNothing>()\n    data object Loading : Result\u003CNothing>()\n}\n\nfun \u003CT> Result\u003CT>.getOrNull(): T? = when (this) {\n    is Result.Success -> data\n    is Result.Failure -> null\n    is Result.Loading -> null\n}\n\nfun \u003CT> Result\u003CT>.getOrThrow(): T = when (this) {\n    is Result.Success -> data\n    is Result.Failure -> throw error.toException()\n    is Result.Loading -> throw IllegalStateException(\"Still loading\")\n}\n```\n\n### API レスポンス用シールドインターフェース\n\n```kotlin\nsealed interface ApiError {\n    val message: String\n\n    data class NotFound(override val message: String) : ApiError\n    data class Unauthorized(override val message: String) : ApiError\n    data class Validation(\n        override val message: String,\n        val field: String,\n    ) : ApiError\n    data class Internal(\n        override val message: String,\n        val cause: Throwable? = null,\n    ) : ApiError\n}\n\nfun ApiError.toStatusCode(): Int = when (this) {\n    is ApiError.NotFound -> 404\n    is ApiError.Unauthorized -> 401\n    is ApiError.Validation -> 422\n    is ApiError.Internal -> 500\n}\n```\n\n## スコープ関数\n\n### それぞれの使用タイミング\n\n```kotlin\n\u002F\u002F let: null 可能またはスコープ付き結果を変換\nval length: Int? = name?.let { it.trim().length }\n\n\u002F\u002F apply: オブジェクトを設定する（オブジェクトを返す）\nval user = User().apply {\n    name = \"Alice\"\n    email = \"alice@example.com\"\n}\n\n\u002F\u002F also: 副作用（オブジェクトを返す）\nval user = createUser(request).also { logger.info(\"Created user: ${it.id}\") }\n\n\u002F\u002F run: レシーバーでブロックを実行（結果を返す）\nval result = connection.run {\n    prepareStatement(sql)\n    executeQuery()\n}\n\n\u002F\u002F with: run の非拡張形式\nval csv = with(StringBuilder()) {\n    appendLine(\"name,email\")\n    users.forEach { appendLine(\"${it.name},${it.email}\") }\n    toString()\n}\n```\n\n### アンチパターン\n\n```kotlin\n\u002F\u002F 悪い例: スコープ関数のネスト\nuser?.let { u ->\n    u.address?.let { addr ->\n        addr.city?.let { city ->\n            println(city) \u002F\u002F 読みにくい\n        }\n    }\n}\n\n\u002F\u002F 良い例: セーフコールチェーンを使用\nval city = user?.address?.city\ncity?.let { println(it) }\n```\n\n## 拡張関数\n\n### 継承なしで機能を追加\n\n```kotlin\n\u002F\u002F 良い例: ドメイン固有の拡張\nfun String.toSlug(): String =\n    lowercase()\n        .replace(Regex(\"[^a-z0-9\\\\s-]\"), \"\")\n        .replace(Regex(\"\\\\s+\"), \"-\")\n        .trim('-')\n\nfun Instant.toLocalDate(zone: ZoneId = ZoneId.systemDefault()): LocalDate =\n    atZone(zone).toLocalDate()\n\n\u002F\u002F 良い例: コレクション拡張\nfun \u003CT> List\u003CT>.second(): T = this[1]\n\nfun \u003CT> List\u003CT>.secondOrNull(): T? = getOrNull(1)\n\n\u002F\u002F 良い例: スコープ付き拡張（グローバル名前空間を汚染しない）\nclass UserService {\n    private fun User.isActive(): Boolean =\n        status == Status.ACTIVE && lastLogin.isAfter(Instant.now().minus(30, ChronoUnit.DAYS))\n\n    fun getActiveUsers(): List\u003CUser> = userRepository.findAll().filter { it.isActive() }\n}\n```\n\n## コルーチン\n\n### 構造化並行性\n\n```kotlin\n\u002F\u002F 良い例: coroutineScope による構造化並行性\nsuspend fun fetchUserWithPosts(userId: String): UserProfile =\n    coroutineScope {\n        val userDeferred = async { userService.getUser(userId) }\n        val postsDeferred = async { postService.getUserPosts(userId) }\n\n        UserProfile(\n            user = userDeferred.await(),\n            posts = postsDeferred.await(),\n        )\n    }\n\n\u002F\u002F 良い例: 子が独立して失敗できる場合は supervisorScope\nsuspend fun fetchDashboard(userId: String): Dashboard =\n    supervisorScope {\n        val user = async { userService.getUser(userId) }\n        val notifications = async { notificationService.getRecent(userId) }\n        val recommendations = async { recommendationService.getFor(userId) }\n\n        Dashboard(\n            user = user.await(),\n            notifications = try {\n                notifications.await()\n            } catch (e: CancellationException) {\n                throw e\n            } catch (e: Exception) {\n                emptyList()\n            },\n            recommendations = try {\n                recommendations.await()\n            } catch (e: CancellationException) {\n                throw e\n            } catch (e: Exception) {\n                emptyList()\n            },\n        )\n    }\n```\n\n### リアクティブストリームのための Flow\n\n```kotlin\n\u002F\u002F 良い例: 適切なエラーハンドリングを持つコールドフロー\nfun observeUsers(): Flow\u003CList\u003CUser>> = flow {\n    while (currentCoroutineContext().isActive) {\n        val users = userRepository.findAll()\n        emit(users)\n        delay(5.seconds)\n    }\n}.catch { e ->\n    logger.error(\"Error observing users\", e)\n    emit(emptyList())\n}\n\n\u002F\u002F 良い例: Flow オペレーター\nfun searchUsers(query: Flow\u003CString>): Flow\u003CList\u003CUser>> =\n    query\n        .debounce(300.milliseconds)\n        .distinctUntilChanged()\n        .filter { it.length >= 2 }\n        .mapLatest { q -> userRepository.search(q) }\n        .catch { emit(emptyList()) }\n```\n\n### キャンセルとクリーンアップ\n\n```kotlin\n\u002F\u002F 良い例: キャンセルを尊重\nsuspend fun processItems(items: List\u003CItem>) {\n    items.forEach { item ->\n        ensureActive() \u002F\u002F 高コストな処理の前にキャンセルを確認\n        processItem(item)\n    }\n}\n\n\u002F\u002F 良い例: try\u002Ffinally でクリーンアップ\nsuspend fun acquireAndProcess() {\n    val resource = acquireResource()\n    try {\n        resource.process()\n    } finally {\n        withContext(NonCancellable) {\n            resource.release() \u002F\u002F キャンセル時でも常に解放\n        }\n    }\n}\n```\n\n## 委譲\n\n### プロパティ委譲\n\n```kotlin\n\u002F\u002F 遅延初期化\nval expensiveData: List\u003CUser> by lazy {\n    userRepository.findAll()\n}\n\n\u002F\u002F 監視可能なプロパティ\nvar name: String by Delegates.observable(\"initial\") { _, old, new ->\n    logger.info(\"Name changed from '$old' to '$new'\")\n}\n\n\u002F\u002F マップバックのプロパティ\nclass Config(private val map: Map\u003CString, Any?>) {\n    val host: String by map\n    val port: Int by map\n    val debug: Boolean by map\n}\n\nval config = Config(mapOf(\"host\" to \"localhost\", \"port\" to 8080, \"debug\" to true))\n```\n\n### インターフェース委譲\n\n```kotlin\n\u002F\u002F 良い例: インターフェース実装を委譲\nclass LoggingUserRepository(\n    private val delegate: UserRepository,\n    private val logger: Logger,\n) : UserRepository by delegate {\n    \u002F\u002F ログを追加する必要があるものだけをオーバーライド\n    override suspend fun findById(id: String): User? {\n        logger.info(\"Finding user by id: $id\")\n        return delegate.findById(id).also {\n            logger.info(\"Found user: ${it?.name ?: \"null\"}\")\n        }\n    }\n}\n```\n\n## DSL ビルダー\n\n### 型安全なビルダー\n\n```kotlin\n\u002F\u002F 良い例: @DslMarker を使用した DSL\n@DslMarker\nannotation class HtmlDsl\n\n@HtmlDsl\nclass HTML {\n    private val children = mutableListOf\u003CElement>()\n\n    fun head(init: Head.() -> Unit) {\n        children += Head().apply(init)\n    }\n\n    fun body(init: Body.() -> Unit) {\n        children += Body().apply(init)\n    }\n\n    override fun toString(): String = children.joinToString(\"\\n\")\n}\n\nfun html(init: HTML.() -> Unit): HTML = HTML().apply(init)\n\n\u002F\u002F 使用例\nval page = html {\n    head { title(\"My Page\") }\n    body {\n        h1(\"Welcome\")\n        p(\"Hello, World!\")\n    }\n}\n```\n\n### 設定 DSL\n\n```kotlin\ndata class ServerConfig(\n    val host: String = \"0.0.0.0\",\n    val port: Int = 8080,\n    val ssl: SslConfig? = null,\n    val database: DatabaseConfig? = null,\n)\n\ndata class SslConfig(val certPath: String, val keyPath: String)\ndata class DatabaseConfig(val url: String, val maxPoolSize: Int = 10)\n\nclass ServerConfigBuilder {\n    var host: String = \"0.0.0.0\"\n    var port: Int = 8080\n    private var ssl: SslConfig? = null\n    private var database: DatabaseConfig? = null\n\n    fun ssl(certPath: String, keyPath: String) {\n        ssl = SslConfig(certPath, keyPath)\n    }\n\n    fun database(url: String, maxPoolSize: Int = 10) {\n        database = DatabaseConfig(url, maxPoolSize)\n    }\n\n    fun build(): ServerConfig = ServerConfig(host, port, ssl, database)\n}\n\nfun serverConfig(init: ServerConfigBuilder.() -> Unit): ServerConfig =\n    ServerConfigBuilder().apply(init).build()\n\n\u002F\u002F 使用例\nval config = serverConfig {\n    host = \"0.0.0.0\"\n    port = 443\n    ssl(\"\u002Fcerts\u002Fcert.pem\", \"\u002Fcerts\u002Fkey.pem\")\n    database(\"jdbc:postgresql:\u002F\u002Flocalhost:5432\u002Fmydb\", maxPoolSize = 20)\n}\n```\n\n## 遅延評価のためのシーケンス\n\n```kotlin\n\u002F\u002F 良い例: 複数の操作を持つ大きなコレクションにはシーケンスを使用\nval result = users.asSequence()\n    .filter { it.isActive }\n    .map { it.email }\n    .filter { it.endsWith(\"@company.com\") }\n    .take(10)\n    .toList()\n\n\u002F\u002F 良い例: 無限シーケンスを生成\nval fibonacci: Sequence\u003CLong> = sequence {\n    var a = 0L\n    var b = 1L\n    while (true) {\n        yield(a)\n        val next = a + b\n        a = b\n        b = next\n    }\n}\n\nval first20 = fibonacci.take(20).toList()\n```\n\n## Gradle Kotlin DSL\n\n### build.gradle.kts 設定\n\n```kotlin\n\u002F\u002F 最新バージョンの確認: https:\u002F\u002Fkotlinlang.org\u002Fdocs\u002Freleases.html\nplugins {\n    kotlin(\"jvm\") version \"2.3.10\"\n    kotlin(\"plugin.serialization\") version \"2.3.10\"\n    id(\"io.ktor.plugin\") version \"3.4.0\"\n    id(\"org.jetbrains.kotlinx.kover\") version \"0.9.7\"\n    id(\"io.gitlab.arturbosch.detekt\") version \"1.23.8\"\n}\n\ngroup = \"com.example\"\nversion = \"1.0.0\"\n\nkotlin {\n    jvmToolchain(21)\n}\n\ndependencies {\n    \u002F\u002F Ktor\n    implementation(\"io.ktor:ktor-server-core:3.4.0\")\n    implementation(\"io.ktor:ktor-server-netty:3.4.0\")\n    implementation(\"io.ktor:ktor-server-content-negotiation:3.4.0\")\n    implementation(\"io.ktor:ktor-serialization-kotlinx-json:3.4.0\")\n\n    \u002F\u002F Exposed\n    implementation(\"org.jetbrains.exposed:exposed-core:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-dao:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-jdbc:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0\")\n\n    \u002F\u002F Koin\n    implementation(\"io.insert-koin:koin-ktor:4.2.0\")\n\n    \u002F\u002F コルーチン\n    implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2\")\n\n    \u002F\u002F テスト\n    testImplementation(\"io.kotest:kotest-runner-junit5:6.1.4\")\n    testImplementation(\"io.kotest:kotest-assertions-core:6.1.4\")\n    testImplementation(\"io.kotest:kotest-property:6.1.4\")\n    testImplementation(\"io.mockk:mockk:1.14.9\")\n    testImplementation(\"io.ktor:ktor-server-test-host:3.4.0\")\n    testImplementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2\")\n}\n\ntasks.withType\u003CTest> {\n    useJUnitPlatform()\n}\n\ndetekt {\n    config.setFrom(files(\"config\u002Fdetekt\u002Fdetekt.yml\"))\n    buildUponDefaultConfig = true\n}\n```\n\n## エラーハンドリングパターン\n\n### ドメイン操作のための Result 型\n\n```kotlin\n\u002F\u002F 良い例: Kotlin の Result またはカスタムシールドクラスを使用\nsuspend fun createUser(request: CreateUserRequest): Result\u003CUser> = runCatching {\n    require(request.name.isNotBlank()) { \"Name cannot be blank\" }\n    require('@' in request.email) { \"Invalid email format\" }\n\n    val user = User(\n        id = UserId(UUID.randomUUID().toString()),\n        name = request.name,\n        email = Email(request.email),\n    )\n    userRepository.save(user)\n    user\n}\n\n\u002F\u002F 良い例: Result をチェーン\nval displayName = createUser(request)\n    .map { it.name }\n    .getOrElse { \"Unknown\" }\n```\n\n### require、check、error\n\n```kotlin\n\u002F\u002F 良い例: 明確なメッセージを持つ事前条件\nfun withdraw(account: Account, amount: Money): Account {\n    require(amount.value > 0) { \"Amount must be positive: $amount\" }\n    check(account.balance >= amount) { \"Insufficient balance: ${account.balance} \u003C $amount\" }\n\n    return account.copy(balance = account.balance - amount)\n}\n```\n\n## コレクション操作\n\n### 慣用的なコレクション処理\n\n```kotlin\n\u002F\u002F 良い例: チェーン操作\nval activeAdminEmails: List\u003CString> = users\n    .filter { it.role == Role.ADMIN && it.isActive }\n    .sortedBy { it.name }\n    .map { it.email }\n\n\u002F\u002F 良い例: グループ化と集計\nval usersByRole: Map\u003CRole, List\u003CUser>> = users.groupBy { it.role }\n\nval oldestByRole: Map\u003CRole, User?> = users.groupBy { it.role }\n    .mapValues { (_, users) -> users.minByOrNull { it.createdAt } }\n\n\u002F\u002F 良い例: マップ作成のための associate\nval usersById: Map\u003CUserId, User> = users.associateBy { it.id }\n\n\u002F\u002F 良い例: 分割のための partition\nval (active, inactive) = users.partition { it.isActive }\n```\n\n## クイックリファレンス: Kotlin イディオム\n\n| イディオム | 説明 |\n|-----------|------|\n| `val` over `var` | イミュータブル変数を優先 |\n| `data class` | equals\u002FhashCode\u002Fcopy を持つ値オブジェクト用 |\n| `sealed class\u002Finterface` | 制限された型階層用 |\n| `value class` | ゼロオーバーヘッドの型安全ラッパー |\n| 式 `when` | 網羅的なパターンマッチング |\n| セーフコール `?.` | null 安全なメンバーアクセス |\n| Elvis `?:` | null 可能型のデフォルト値 |\n| `let`\u002F`apply`\u002F`also`\u002F`run`\u002F`with` | クリーンなコードのためのスコープ関数 |\n| 拡張関数 | 継承なしで振る舞いを追加 |\n| `copy()` | データクラスのイミュータブルな更新 |\n| `require`\u002F`check` | 事前条件アサーション |\n| コルーチン `async`\u002F`await` | 構造化された並行実行 |\n| `Flow` | コールドリアクティブストリーム |\n| `sequence` | 遅延評価 |\n| 委譲 `by` | 継承なしで実装を再利用 |\n\n## 避けるべきアンチパターン\n\n```kotlin\n\u002F\u002F 悪い例: null 可能型を強制アンラップ\nval name = user!!.name\n\n\u002F\u002F 悪い例: Java からのプラットフォーム型リーク\nfun getLength(s: String) = s.length \u002F\u002F 安全\nfun getLength(s: String?) = s?.length ?: 0 \u002F\u002F Java からの null を処理\n\n\u002F\u002F 悪い例: ミュータブルなデータクラス\ndata class MutableUser(var name: String, var email: String)\n\n\u002F\u002F 悪い例: 制御フローに例外を使用\ntry {\n    val user = findUser(id)\n} catch (e: NotFoundException) {\n    \u002F\u002F 期待されるケースに例外を使用しない\n}\n\n\u002F\u002F 良い例: null 可能な戻り値または Result を使用\nval user: User? = findUserOrNull(id)\n\n\u002F\u002F 悪い例: コルーチンスコープを無視\nGlobalScope.launch { \u002F* GlobalScope を避ける *\u002F }\n\n\u002F\u002F 良い例: 構造化並行性を使用\ncoroutineScope {\n    launch { \u002F* 適切にスコープ化 *\u002F }\n}\n\n\u002F\u002F 悪い例: 深くネストされたスコープ関数\nuser?.let { u ->\n    u.address?.let { a ->\n        a.city?.let { c -> process(c) }\n    }\n}\n\n\u002F\u002F 良い例: 直接のセーフコールチェーン\nuser?.address?.city?.let { process(it) }\n```\n\n**覚えておくこと**: Kotlin のコードは簡潔かつ読みやすくあるべきです。安全性のために型システムを活用し、イミュータビリティを優先し、並行性にはコルーチンを使用してください。迷ったときはコンパイラに助けてもらいましょう。\n","# Kotlin 開発パターン\n\n堅牢・効率的・保守性の高いアプリケーションを構築するための慣用的な Kotlin パターンとベストプラクティス。\n\n## 使用するタイミング\n\n- 新しい Kotlin コードを書く\n- Kotlin コードをレビューする\n- 既存の Kotlin コードをリファクタリングする\n- Kotlin モジュールまたはライブラリを設計する\n- Gradle Kotlin DSL ビルドを設定する\n\n## 動作の仕組み\n\nこのスキルは 7 つの主要領域にわたって慣用的な Kotlin の規約を適用します: 型システムとセーフコール演算子を使用した null 安全性、`val` とデータクラスの `copy()` によるイミュータビリティ、網羅的な型階層のためのシールドクラスとインターフェース、コルーチンと `Flow` による構造化並行性、継承なしで振る舞いを追加する拡張関数、`@DslMarker` とラムダレシーバーを使用した型安全 DSL ビルダー、そしてビルド設定のための Gradle Kotlin DSL。\n\n## 使用例\n\n**Elvis 演算子を使用した null 安全性:**\n```kotlin\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n```\n\n**網羅的な結果のためのシールドクラス:**\n```kotlin\nsealed class Result\u003Cout T> {\n    data class Success\u003CT>(val data: T) : Result\u003CT>()\n    data class Failure(val error: AppError) : Result\u003CNothing>()\n    data object Loading : Result\u003CNothing>()\n}\n```\n\n**async\u002Fawait を使用した構造化並行性:**\n```kotlin\nsuspend fun fetchUserWithPosts(userId: String): UserProfile =\n    coroutineScope {\n        val user = async { userService.getUser(userId) }\n        val posts = async { postService.getUserPosts(userId) }\n        UserProfile(user = user.await(), posts = posts.await())\n    }\n```\n\n## コア原則\n\n### 1. Null 安全性\n\nKotlin の型システムは null 可能型と非 null 型を区別します。これを最大限に活用してください。\n\n```kotlin\n\u002F\u002F 良い例: デフォルトで非 null 型を使用\nfun getUser(id: String): User {\n    return userRepository.findById(id)\n        ?: throw UserNotFoundException(\"User $id not found\")\n}\n\n\u002F\u002F 良い例: セーフコールと Elvis 演算子\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n\n\u002F\u002F 悪い例: null 可能型を強制アンラップ\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user!!.email \u002F\u002F null の場合 NPE をスロー\n}\n```\n\n### 2. デフォルトでイミュータブル\n\n`var` より `val` を優先し、ミュータブルコレクションよりイミュータブルコレクションを優先してください。\n\n```kotlin\n\u002F\u002F 良い例: イミュータブルデータ\ndata class User(\n    val id: String,\n    val name: String,\n    val email: String,\n)\n\n\u002F\u002F 良い例: copy() で変換\nfun updateEmail(user: User, newEmail: String): User =\n    user.copy(email = newEmail)\n\n\u002F\u002F 良い例: イミュータブルコレクション\nval users: List\u003CUser> = listOf(user1, user2)\nval filtered = users.filter { it.email.isNotBlank() }\n\n\u002F\u002F 悪い例: ミュータブルな状態\nvar currentUser: User? = null \u002F\u002F ミュータブルなグローバル状態を避ける\nval mutableUsers = mutableListOf\u003CUser>() \u002F\u002F 本当に必要な場合のみ使用\n```\n\n### 3. 式ボディと単一式関数\n\n簡潔で読みやすい関数には式ボディを使用してください。\n\n```kotlin\n\u002F\u002F 良い例: 式ボディ\nfun isAdult(age: Int): Boolean = age >= 18\n\nfun formatFullName(first: String, last: String): String =\n    \"$first $last\".trim()\n\nfun User.displayName(): String =\n    name.ifBlank { email.substringBefore('@') }\n\n\u002F\u002F 良い例: 式としての when\nfun statusMessage(code: Int): String = when (code) {\n    200 -> \"OK\"\n    404 -> \"Not Found\"\n    500 -> \"Internal Server Error\"\n    else -> \"Unknown status: $code\"\n}\n\n\u002F\u002F 悪い例: 不要なブロックボディ\nfun isAdult(age: Int): Boolean {\n    return age >= 18\n}\n```\n\n### 4. 値オブジェクトのためのデータクラス\n\n主にデータを保持する型にはデータクラスを使用してください。\n\n```kotlin\n\u002F\u002F 良い例: copy、equals、hashCode、toString を持つデータクラス\ndata class CreateUserRequest(\n    val name: String,\n    val email: String,\n    val role: Role = Role.USER,\n)\n\n\u002F\u002F 良い例: 型安全性のための値クラス（ランタイムでゼロオーバーヘッド）\n@JvmInline\nvalue class UserId(val value: String) {\n    init {\n        require(value.isNotBlank()) { \"UserId cannot be blank\" }\n    }\n}\n\n@JvmInline\nvalue class Email(val value: String) {\n    init {\n        require('@' in value) { \"Invalid email: $value\" }\n    }\n}\n\nfun getUser(id: UserId): User = userRepository.findById(id)\n```\n\n## シールドクラスとインターフェース\n\n### 制限された階層のモデリング\n\n```kotlin\n\u002F\u002F 良い例: 網羅的な when のためのシールドクラス\nsealed class Result\u003Cout T> {\n    data class Success\u003CT>(val data: T) : Result\u003CT>()\n    data class Failure(val error: AppError) : Result\u003CNothing>()\n    data object Loading : Result\u003CNothing>()\n}\n\nfun \u003CT> Result\u003CT>.getOrNull(): T? = when (this) {\n    is Result.Success -> data\n    is Result.Failure -> null\n    is Result.Loading -> null\n}\n\nfun \u003CT> Result\u003CT>.getOrThrow(): T = when (this) {\n    is Result.Success -> data\n    is Result.Failure -> throw error.toException()\n    is Result.Loading -> throw IllegalStateException(\"Still loading\")\n}\n```\n\n### API レスポンス用シールドインターフェース\n\n```kotlin\nsealed interface ApiError {\n    val message: String\n\n    data class NotFound(override val message: String) : ApiError\n    data class Unauthorized(override val message: String) : ApiError\n    data class Validation(\n        override val message: String,\n        val field: String,\n    ) : ApiError\n    data class Internal(\n        override val message: String,\n        val cause: Throwable? = null,\n    ) : ApiError\n}\n\nfun ApiError.toStatusCode(): Int = when (this) {\n    is ApiError.NotFound -> 404\n    is ApiError.Unauthorized -> 401\n    is ApiError.Validation -> 422\n    is ApiError.Internal -> 500\n}\n```\n\n## スコープ関数\n\n### それぞれの使用タイミング\n\n```kotlin\n\u002F\u002F let: null 可能またはスコープ付き結果を変換\nval length: Int? = name?.let { it.trim().length }\n\n\u002F\u002F apply: オブジェクトを設定する（オブジェクトを返す）\nval user = User().apply {\n    name = \"Alice\"\n    email = \"alice@example.com\"\n}\n\n\u002F\u002F also: 副作用（オブジェクトを返す）\nval user = createUser(request).also { logger.info(\"Created user: ${it.id}\") }\n\n\u002F\u002F run: レシーバーでブロックを実行（結果を返す）\nval result = connection.run {\n    prepareStatement(sql)\n    executeQuery()\n}\n\n\u002F\u002F with: run の非拡張形式\nval csv = with(StringBuilder()) {\n    appendLine(\"name,email\")\n    users.forEach { appendLine(\"${it.name},${it.email}\") }\n    toString()\n}\n```\n\n### アンチパターン\n\n```kotlin\n\u002F\u002F 悪い例: スコープ関数のネスト\nuser?.let { u ->\n    u.address?.let { addr ->\n        addr.city?.let { city ->\n            println(city) \u002F\u002F 読みにくい\n        }\n    }\n}\n\n\u002F\u002F 良い例: セーフコールチェーンを使用\nval city = user?.address?.city\ncity?.let { println(it) }\n```\n\n## 拡張関数\n\n### 継承なしで機能を追加\n\n```kotlin\n\u002F\u002F 良い例: ドメイン固有の拡張\nfun String.toSlug(): String =\n    lowercase()\n        .replace(Regex(\"[^a-z0-9\\\\s-]\"), \"\")\n        .replace(Regex(\"\\\\s+\"), \"-\")\n        .trim('-')\n\nfun Instant.toLocalDate(zone: ZoneId = ZoneId.systemDefault()): LocalDate =\n    atZone(zone).toLocalDate()\n\n\u002F\u002F 良い例: コレクション拡張\nfun \u003CT> List\u003CT>.second(): T = this[1]\n\nfun \u003CT> List\u003CT>.secondOrNull(): T? = getOrNull(1)\n\n\u002F\u002F 良い例: スコープ付き拡張（グローバル名前空間を汚染しない）\nclass UserService {\n    private fun User.isActive(): Boolean =\n        status == Status.ACTIVE && lastLogin.isAfter(Instant.now().minus(30, ChronoUnit.DAYS))\n\n    fun getActiveUsers(): List\u003CUser> = userRepository.findAll().filter { it.isActive() }\n}\n```\n\n## コルーチン\n\n### 構造化並行性\n\n```kotlin\n\u002F\u002F 良い例: coroutineScope による構造化並行性\nsuspend fun fetchUserWithPosts(userId: String): UserProfile =\n    coroutineScope {\n        val userDeferred = async { userService.getUser(userId) }\n        val postsDeferred = async { postService.getUserPosts(userId) }\n\n        UserProfile(\n            user = userDeferred.await(),\n            posts = postsDeferred.await(),\n        )\n    }\n\n\u002F\u002F 良い例: 子が独立して失敗できる場合は supervisorScope\nsuspend fun fetchDashboard(userId: String): Dashboard =\n    supervisorScope {\n        val user = async { userService.getUser(userId) }\n        val notifications = async { notificationService.getRecent(userId) }\n        val recommendations = async { recommendationService.getFor(userId) }\n\n        Dashboard(\n            user = user.await(),\n            notifications = try {\n                notifications.await()\n            } catch (e: CancellationException) {\n                throw e\n            } catch (e: Exception) {\n                emptyList()\n            },\n            recommendations = try {\n                recommendations.await()\n            } catch (e: CancellationException) {\n                throw e\n            } catch (e: Exception) {\n                emptyList()\n            },\n        )\n    }\n```\n\n### リアクティブストリームのための Flow\n\n```kotlin\n\u002F\u002F 良い例: 適切なエラーハンドリングを持つコールドフロー\nfun observeUsers(): Flow\u003CList\u003CUser>> = flow {\n    while (currentCoroutineContext().isActive) {\n        val users = userRepository.findAll()\n        emit(users)\n        delay(5.seconds)\n    }\n}.catch { e ->\n    logger.error(\"Error observing users\", e)\n    emit(emptyList())\n}\n\n\u002F\u002F 良い例: Flow オペレーター\nfun searchUsers(query: Flow\u003CString>): Flow\u003CList\u003CUser>> =\n    query\n        .debounce(300.milliseconds)\n        .distinctUntilChanged()\n        .filter { it.length >= 2 }\n        .mapLatest { q -> userRepository.search(q) }\n        .catch { emit(emptyList()) }\n```\n\n### キャンセルとクリーンアップ\n\n```kotlin\n\u002F\u002F 良い例: キャンセルを尊重\nsuspend fun processItems(items: List\u003CItem>) {\n    items.forEach { item ->\n        ensureActive() \u002F\u002F 高コストな処理の前にキャンセルを確認\n        processItem(item)\n    }\n}\n\n\u002F\u002F 良い例: try\u002Ffinally でクリーンアップ\nsuspend fun acquireAndProcess() {\n    val resource = acquireResource()\n    try {\n        resource.process()\n    } finally {\n        withContext(NonCancellable) {\n            resource.release() \u002F\u002F キャンセル時でも常に解放\n        }\n    }\n}\n```\n\n## 委譲\n\n### プロパティ委譲\n\n```kotlin\n\u002F\u002F 遅延初期化\nval expensiveData: List\u003CUser> by lazy {\n    userRepository.findAll()\n}\n\n\u002F\u002F 監視可能なプロパティ\nvar name: String by Delegates.observable(\"initial\") { _, old, new ->\n    logger.info(\"Name changed from '$old' to '$new'\")\n}\n\n\u002F\u002F マップバックのプロパティ\nclass Config(private val map: Map\u003CString, Any?>) {\n    val host: String by map\n    val port: Int by map\n    val debug: Boolean by map\n}\n\nval config = Config(mapOf(\"host\" to \"localhost\", \"port\" to 8080, \"debug\" to true))\n```\n\n### インターフェース委譲\n\n```kotlin\n\u002F\u002F 良い例: インターフェース実装を委譲\nclass LoggingUserRepository(\n    private val delegate: UserRepository,\n    private val logger: Logger,\n) : UserRepository by delegate {\n    \u002F\u002F ログを追加する必要があるものだけをオーバーライド\n    override suspend fun findById(id: String): User? {\n        logger.info(\"Finding user by id: $id\")\n        return delegate.findById(id).also {\n            logger.info(\"Found user: ${it?.name ?: \"null\"}\")\n        }\n    }\n}\n```\n\n## DSL ビルダー\n\n### 型安全なビルダー\n\n```kotlin\n\u002F\u002F 良い例: @DslMarker を使用した DSL\n@DslMarker\nannotation class HtmlDsl\n\n@HtmlDsl\nclass HTML {\n    private val children = mutableListOf\u003CElement>()\n\n    fun head(init: Head.() -> Unit) {\n        children += Head().apply(init)\n    }\n\n    fun body(init: Body.() -> Unit) {\n        children += Body().apply(init)\n    }\n\n    override fun toString(): String = children.joinToString(\"\\n\")\n}\n\nfun html(init: HTML.() -> Unit): HTML = HTML().apply(init)\n\n\u002F\u002F 使用例\nval page = html {\n    head { title(\"My Page\") }\n    body {\n        h1(\"Welcome\")\n        p(\"Hello, World!\")\n    }\n}\n```\n\n### 設定 DSL\n\n```kotlin\ndata class ServerConfig(\n    val host: String = \"0.0.0.0\",\n    val port: Int = 8080,\n    val ssl: SslConfig? = null,\n    val database: DatabaseConfig? = null,\n)\n\ndata class SslConfig(val certPath: String, val keyPath: String)\ndata class DatabaseConfig(val url: String, val maxPoolSize: Int = 10)\n\nclass ServerConfigBuilder {\n    var host: String = \"0.0.0.0\"\n    var port: Int = 8080\n    private var ssl: SslConfig? = null\n    private var database: DatabaseConfig? = null\n\n    fun ssl(certPath: String, keyPath: String) {\n        ssl = SslConfig(certPath, keyPath)\n    }\n\n    fun database(url: String, maxPoolSize: Int = 10) {\n        database = DatabaseConfig(url, maxPoolSize)\n    }\n\n    fun build(): ServerConfig = ServerConfig(host, port, ssl, database)\n}\n\nfun serverConfig(init: ServerConfigBuilder.() -> Unit): ServerConfig =\n    ServerConfigBuilder().apply(init).build()\n\n\u002F\u002F 使用例\nval config = serverConfig {\n    host = \"0.0.0.0\"\n    port = 443\n    ssl(\"\u002Fcerts\u002Fcert.pem\", \"\u002Fcerts\u002Fkey.pem\")\n    database(\"jdbc:postgresql:\u002F\u002Flocalhost:5432\u002Fmydb\", maxPoolSize = 20)\n}\n```\n\n## 遅延評価のためのシーケンス\n\n```kotlin\n\u002F\u002F 良い例: 複数の操作を持つ大きなコレクションにはシーケンスを使用\nval result = users.asSequence()\n    .filter { it.isActive }\n    .map { it.email }\n    .filter { it.endsWith(\"@company.com\") }\n    .take(10)\n    .toList()\n\n\u002F\u002F 良い例: 無限シーケンスを生成\nval fibonacci: Sequence\u003CLong> = sequence {\n    var a = 0L\n    var b = 1L\n    while (true) {\n        yield(a)\n        val next = a + b\n        a = b\n        b = next\n    }\n}\n\nval first20 = fibonacci.take(20).toList()\n```\n\n## Gradle Kotlin DSL\n\n### build.gradle.kts 設定\n\n```kotlin\n\u002F\u002F 最新バージョンの確認: https:\u002F\u002Fkotlinlang.org\u002Fdocs\u002Freleases.html\nplugins {\n    kotlin(\"jvm\") version \"2.3.10\"\n    kotlin(\"plugin.serialization\") version \"2.3.10\"\n    id(\"io.ktor.plugin\") version \"3.4.0\"\n    id(\"org.jetbrains.kotlinx.kover\") version \"0.9.7\"\n    id(\"io.gitlab.arturbosch.detekt\") version \"1.23.8\"\n}\n\ngroup = \"com.example\"\nversion = \"1.0.0\"\n\nkotlin {\n    jvmToolchain(21)\n}\n\ndependencies {\n    \u002F\u002F Ktor\n    implementation(\"io.ktor:ktor-server-core:3.4.0\")\n    implementation(\"io.ktor:ktor-server-netty:3.4.0\")\n    implementation(\"io.ktor:ktor-server-content-negotiation:3.4.0\")\n    implementation(\"io.ktor:ktor-serialization-kotlinx-json:3.4.0\")\n\n    \u002F\u002F Exposed\n    implementation(\"org.jetbrains.exposed:exposed-core:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-dao:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-jdbc:1.0.0\")\n    implementation(\"org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0\")\n\n    \u002F\u002F Koin\n    implementation(\"io.insert-koin:koin-ktor:4.2.0\")\n\n    \u002F\u002F コルーチン\n    implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2\")\n\n    \u002F\u002F テスト\n    testImplementation(\"io.kotest:kotest-runner-junit5:6.1.4\")\n    testImplementation(\"io.kotest:kotest-assertions-core:6.1.4\")\n    testImplementation(\"io.kotest:kotest-property:6.1.4\")\n    testImplementation(\"io.mockk:mockk:1.14.9\")\n    testImplementation(\"io.ktor:ktor-server-test-host:3.4.0\")\n    testImplementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2\")\n}\n\ntasks.withType\u003CTest> {\n    useJUnitPlatform()\n}\n\ndetekt {\n    config.setFrom(files(\"config\u002Fdetekt\u002Fdetekt.yml\"))\n    buildUponDefaultConfig = true\n}\n```\n\n## エラーハンドリングパターン\n\n### ドメイン操作のための Result 型\n\n```kotlin\n\u002F\u002F 良い例: Kotlin の Result またはカスタムシールドクラスを使用\nsuspend fun createUser(request: CreateUserRequest): Result\u003CUser> = runCatching {\n    require(request.name.isNotBlank()) { \"Name cannot be blank\" }\n    require('@' in request.email) { \"Invalid email format\" }\n\n    val user = User(\n        id = UserId(UUID.randomUUID().toString()),\n        name = request.name,\n        email = Email(request.email),\n    )\n    userRepository.save(user)\n    user\n}\n\n\u002F\u002F 良い例: Result をチェーン\nval displayName = createUser(request)\n    .map { it.name }\n    .getOrElse { \"Unknown\" }\n```\n\n### require、check、error\n\n```kotlin\n\u002F\u002F 良い例: 明確なメッセージを持つ事前条件\nfun withdraw(account: Account, amount: Money): Account {\n    require(amount.value > 0) { \"Amount must be positive: $amount\" }\n    check(account.balance >= amount) { \"Insufficient balance: ${account.balance} \u003C $amount\" }\n\n    return account.copy(balance = account.balance - amount)\n}\n```\n\n## コレクション操作\n\n### 慣用的なコレクション処理\n\n```kotlin\n\u002F\u002F 良い例: チェーン操作\nval activeAdminEmails: List\u003CString> = users\n    .filter { it.role == Role.ADMIN && it.isActive }\n    .sortedBy { it.name }\n    .map { it.email }\n\n\u002F\u002F 良い例: グループ化と集計\nval usersByRole: Map\u003CRole, List\u003CUser>> = users.groupBy { it.role }\n\nval oldestByRole: Map\u003CRole, User?> = users.groupBy { it.role }\n    .mapValues { (_, users) -> users.minByOrNull { it.createdAt } }\n\n\u002F\u002F 良い例: マップ作成のための associate\nval usersById: Map\u003CUserId, User> = users.associateBy { it.id }\n\n\u002F\u002F 良い例: 分割のための partition\nval (active, inactive) = users.partition { it.isActive }\n```\n\n## クイックリファレンス: Kotlin イディオム\n\n| イディオム | 説明 |\n|-----------|------|\n| `val` over `var` | イミュータブル変数を優先 |\n| `data class` | equals\u002FhashCode\u002Fcopy を持つ値オブジェクト用 |\n| `sealed class\u002Finterface` | 制限された型階層用 |\n| `value class` | ゼロオーバーヘッドの型安全ラッパー |\n| 式 `when` | 網羅的なパターンマッチング |\n| セーフコール `?.` | null 安全なメンバーアクセス |\n| Elvis `?:` | null 可能型のデフォルト値 |\n| `let`\u002F`apply`\u002F`also`\u002F`run`\u002F`with` | クリーンなコードのためのスコープ関数 |\n| 拡張関数 | 継承なしで振る舞いを追加 |\n| `copy()` | データクラスのイミュータブルな更新 |\n| `require`\u002F`check` | 事前条件アサーション |\n| コルーチン `async`\u002F`await` | 構造化された並行実行 |\n| `Flow` | コールドリアクティブストリーム |\n| `sequence` | 遅延評価 |\n| 委譲 `by` | 継承なしで実装を再利用 |\n\n## 避けるべきアンチパターン\n\n```kotlin\n\u002F\u002F 悪い例: null 可能型を強制アンラップ\nval name = user!!.name\n\n\u002F\u002F 悪い例: Java からのプラットフォーム型リーク\nfun getLength(s: String) = s.length \u002F\u002F 安全\nfun getLength(s: String?) = s?.length ?: 0 \u002F\u002F Java からの null を処理\n\n\u002F\u002F 悪い例: ミュータブルなデータクラス\ndata class MutableUser(var name: String, var email: String)\n\n\u002F\u002F 悪い例: 制御フローに例外を使用\ntry {\n    val user = findUser(id)\n} catch (e: NotFoundException) {\n    \u002F\u002F 期待されるケースに例外を使用しない\n}\n\n\u002F\u002F 良い例: null 可能な戻り値または Result を使用\nval user: User? = findUserOrNull(id)\n\n\u002F\u002F 悪い例: コルーチンスコープを無視\nGlobalScope.launch { \u002F* GlobalScope を避ける *\u002F }\n\n\u002F\u002F 良い例: 構造化並行性を使用\ncoroutineScope {\n    launch { \u002F* 適切にスコープ化 *\u002F }\n}\n\n\u002F\u002F 悪い例: 深くネストされたスコープ関数\nuser?.let { u ->\n    u.address?.let { a ->\n        a.city?.let { c -> process(c) }\n    }\n}\n\n\u002F\u002F 良い例: 直接のセーフコールチェーン\nuser?.address?.city?.let { process(it) }\n```\n\n**覚えておくこと**: Kotlin のコードは簡潔かつ読みやすくあるべきです。安全性のために型システムを活用し、イミュータビリティを優先し、並行性にはコルーチンを使用してください。迷ったときはコンパイラに助けてもらいましょう。\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fkotlin-patterns",0,"https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee","https:\u002F\u002Fwithcyril.me\u002F","Hi, I’m Julian Cyril D, a Computer Science and Business Systems student at PSNACET.\r\nI’m passionate about full-stack development, UI\u002FUX design, and building sma","2026-11-04 23:28:50",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Cyrilthetecchieee\u002Fcyril-code- --skill kotlin-patterns",{"tool":40,"command":41},"bunx","bunx skills add Cyrilthetecchieee\u002Fcyril-code- --skill kotlin-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Cyrilthetecchieee\u002Fcyril-code- --skill kotlin-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fkotlin-patterns\u002FSKILL.md",true,[],[49,58,65,73,80,87],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":54,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7AQV6CYX8RMC78420V9WZ62","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AQV2895N3S1MEX6K76G6G2","youtube-downloader","Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fvideo-downloader\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AQTRNX62DNKVZ5GXEHRBKB","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AQTNNVHAAN9H6DA8T6ZVE0","template-skill","Replace with description of the skill and when Claude should use it.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftemplate-skill\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AQTJ3MQ6AKX152MEX2MYCC","tailored-resume-generator","Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftailored-resume-generator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7AQTD7D5MYET2YWG7HG9WM3","slack-gif-creator","Toolkit for creating animated GIFs optimized for Slack, with validators for size constraints and composable animation primitives. This skill applies when users request animated GIFs or emoji animations for Slack from descriptions like \"make me a GIF for Slack of X doing Y\".","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FSKILL.md",[],[]]