[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AJXTQJFDVPSHXX4Z58D6EC":3,"skill-same:01M7AJXTQJFDVPSHXX4Z58D6EC":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},"01M7AJXTQJFDVPSHXX4Z58D6EC","kotlin-patterns",null,"Patrones idiomáticos de Kotlin, buenas prácticas y convenciones para construir aplicaciones Kotlin robustas, eficientes y mantenibles con coroutines, null safety y builders de DSL.","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\u002Fes\u002Fskills\u002Fkotlin-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: kotlin-patterns\ndescription: Patrones idiomáticos de Kotlin, buenas prácticas y convenciones para construir aplicaciones Kotlin robustas, eficientes y mantenibles con coroutines, null safety y builders de DSL.\norigin: ECC\n---\n\n# Patrones de Desarrollo Kotlin\n\nPatrones idiomáticos de Kotlin y buenas prácticas para construir aplicaciones robustas, eficientes y mantenibles.\n\n## Cuándo Usar\n\n- Escribir nuevo código Kotlin\n- Revisar código Kotlin\n- Refactorizar código Kotlin existente\n- Diseñar módulos o librerías Kotlin\n- Configurar builds con Gradle Kotlin DSL\n\n## Cómo Funciona\n\nEste skill aplica convenciones idiomáticas de Kotlin en siete áreas clave: null safety usando el sistema de tipos y operadores de llamada segura, inmutabilidad mediante `val` y `copy()` en data classes, clases selladas e interfaces para jerarquías de tipos exhaustivas, concurrencia estructurada con coroutines y `Flow`, funciones de extensión para agregar comportamiento sin herencia, builders de DSL type-safe usando `@DslMarker` y receptores lambda, y Gradle Kotlin DSL para configuración de build.\n\n## Ejemplos\n\n**Null safety con el operador Elvis:**\n```kotlin\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n```\n\n**Sealed class para resultados exhaustivos:**\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**Concurrencia estructurada con 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## Principios Fundamentales\n\n### 1. Null Safety\n\nEl sistema de tipos de Kotlin distingue tipos nullable de no-nullable. Aprovecharlo al máximo.\n\n```kotlin\n\u002F\u002F Bien: Usar tipos no-nullable por defecto\nfun getUser(id: String): User {\n    return userRepository.findById(id)\n        ?: throw UserNotFoundException(\"User $id not found\")\n}\n\n\u002F\u002F Bien: Llamadas seguras y operador Elvis\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n\n\u002F\u002F Mal: Desempaquetar forzadamente tipos nullable\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user!!.email \u002F\u002F Lanza NPE si es null\n}\n```\n\n### 2. Inmutabilidad por Defecto\n\nPreferir `val` sobre `var`, colecciones inmutables sobre mutables.\n\n```kotlin\n\u002F\u002F Bien: Datos inmutables\ndata class User(\n    val id: String,\n    val name: String,\n    val email: String,\n)\n\n\u002F\u002F Bien: Transformar con copy()\nfun updateEmail(user: User, newEmail: String): User =\n    user.copy(email = newEmail)\n\n\u002F\u002F Bien: Colecciones inmutables\nval users: List\u003CUser> = listOf(user1, user2)\nval filtered = users.filter { it.email.isNotBlank() }\n\n\u002F\u002F Mal: Estado mutable\nvar currentUser: User? = null \u002F\u002F Evitar estado global mutable\nval mutableUsers = mutableListOf\u003CUser>() \u002F\u002F Evitar a menos que sea realmente necesario\n```\n\n### 3. Cuerpos de Expresión y Funciones de Una Sola Expresión\n\nUsar cuerpos de expresión para funciones concisas y legibles.\n\n```kotlin\n\u002F\u002F Bien: Cuerpo de expresión\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 Bien: When como expresión\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 Mal: Cuerpo de bloque innecesario\nfun isAdult(age: Int): Boolean {\n    return age >= 18\n}\n```\n\n### 4. Data Classes para Objetos de Valor\n\nUsar data classes para tipos que principalmente contienen datos.\n\n```kotlin\n\u002F\u002F Bien: Data class con 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 Bien: Value class para type safety (cero overhead en tiempo de ejecución)\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## Clases Selladas e Interfaces\n\n### Modelar Jerarquías Restringidas\n\n```kotlin\n\u002F\u002F Bien: Sealed class para when exhaustivo\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### Sealed Interfaces para Respuestas de 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## Funciones de Scope\n\n### Cuándo Usar Cada Una\n\n```kotlin\n\u002F\u002F let: Transformar resultado nullable o delimitado\nval length: Int? = name?.let { it.trim().length }\n\n\u002F\u002F apply: Configurar un objeto (retorna el objeto)\nval user = User().apply {\n    name = \"Alice\"\n    email = \"alice@example.com\"\n}\n\n\u002F\u002F also: Efectos secundarios (retorna el objeto)\nval user = createUser(request).also { logger.info(\"Created user: ${it.id}\") }\n\n\u002F\u002F run: Ejecutar un bloque con receptor (retorna resultado)\nval result = connection.run {\n    prepareStatement(sql)\n    executeQuery()\n}\n\n\u002F\u002F with: Forma no-extensión de run\nval csv = with(StringBuilder()) {\n    appendLine(\"name,email\")\n    users.forEach { appendLine(\"${it.name},${it.email}\") }\n    toString()\n}\n```\n\n### Anti-Patrones\n\n```kotlin\n\u002F\u002F Mal: Anidar funciones de scope\nuser?.let { u ->\n    u.address?.let { addr ->\n        addr.city?.let { city ->\n            println(city) \u002F\u002F Difícil de leer\n        }\n    }\n}\n\n\u002F\u002F Bien: Encadenar llamadas seguras en su lugar\nval city = user?.address?.city\ncity?.let { println(it) }\n```\n\n## Funciones de Extensión\n\n### Agregar Funcionalidad Sin Herencia\n\n```kotlin\n\u002F\u002F Bien: Extensiones específicas del dominio\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 Bien: Extensiones de colecciones\nfun \u003CT> List\u003CT>.second(): T = this[1]\n\nfun \u003CT> List\u003CT>.secondOrNull(): T? = getOrNull(1)\n\n\u002F\u002F Bien: Extensiones delimitadas (sin contaminar el namespace global)\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## Coroutines\n\n### Concurrencia Estructurada\n\n```kotlin\n\u002F\u002F Bien: Concurrencia estructurada con 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 Bien: supervisorScope cuando los hijos pueden fallar independientemente\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 para Streams Reactivos\n\n```kotlin\n\u002F\u002F Bien: Flow frío con manejo de errores adecuado\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 Bien: Operadores de 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### Cancelación y Limpieza\n\n```kotlin\n\u002F\u002F Bien: Respetar la cancelación\nsuspend fun processItems(items: List\u003CItem>) {\n    items.forEach { item ->\n        ensureActive() \u002F\u002F Verificar cancelación antes del trabajo costoso\n        processItem(item)\n    }\n}\n\n\u002F\u002F Bien: Limpieza con try\u002Ffinally\nsuspend fun acquireAndProcess() {\n    val resource = acquireResource()\n    try {\n        resource.process()\n    } finally {\n        withContext(NonCancellable) {\n            resource.release() \u002F\u002F Siempre liberar, incluso al cancelar\n        }\n    }\n}\n```\n\n## Delegación\n\n### Delegación de Propiedades\n\n```kotlin\n\u002F\u002F Inicialización diferida\nval expensiveData: List\u003CUser> by lazy {\n    userRepository.findAll()\n}\n\n\u002F\u002F Propiedad observable\nvar name: String by Delegates.observable(\"initial\") { _, old, new ->\n    logger.info(\"Name changed from '$old' to '$new'\")\n}\n\n\u002F\u002F Propiedades respaldadas por Map\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### Delegación de Interfaces\n\n```kotlin\n\u002F\u002F Bien: Delegar implementación de interfaz\nclass LoggingUserRepository(\n    private val delegate: UserRepository,\n    private val logger: Logger,\n) : UserRepository by delegate {\n    \u002F\u002F Solo sobreescribir lo que necesitas agregar logging\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## Builders de DSL\n\n### Builders Type-Safe\n\n```kotlin\n\u002F\u002F Bien: DSL con @DslMarker\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 Uso\nval page = html {\n    head { title(\"My Page\") }\n    body {\n        h1(\"Welcome\")\n        p(\"Hello, World!\")\n    }\n}\n```\n\n### DSL de Configuración\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 Uso\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## Secuencias para Evaluación Diferida\n\n```kotlin\n\u002F\u002F Bien: Usar secuencias para colecciones grandes con múltiples operaciones\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 Bien: Generar secuencias infinitas\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### Configuración de build.gradle.kts\n\n```kotlin\n\u002F\u002F Verificar las últimas versiones: 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 Coroutines\n    implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2\")\n\n    \u002F\u002F Pruebas\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## Patrones de Manejo de Errores\n\n### Tipo Result para Operaciones de Dominio\n\n```kotlin\n\u002F\u002F Bien: Usar Result de Kotlin o una sealed class personalizada\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 Bien: Encadenar resultados\nval displayName = createUser(request)\n    .map { it.name }\n    .getOrElse { \"Unknown\" }\n```\n\n### require, check, error\n\n```kotlin\n\u002F\u002F Bien: Precondiciones con mensajes claros\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## Operaciones de Colecciones\n\n### Procesamiento Idiomático de Colecciones\n\n```kotlin\n\u002F\u002F Bien: Operaciones encadenadas\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 Bien: Agrupación y agregación\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 Bien: Associate para creación de maps\nval usersById: Map\u003CUserId, User> = users.associateBy { it.id }\n\n\u002F\u002F Bien: Partition para dividir\nval (active, inactive) = users.partition { it.isActive }\n```\n\n## Referencia Rápida: Modismos de Kotlin\n\n| Modismo | Descripción |\n|---------|-------------|\n| `val` sobre `var` | Preferir variables inmutables |\n| `data class` | Para objetos de valor con equals\u002FhashCode\u002Fcopy |\n| `sealed class\u002Finterface` | Para jerarquías de tipos restringidas |\n| `value class` | Para wrappers type-safe con cero overhead |\n| `when` expresión | Pattern matching exhaustivo |\n| Llamada segura `?.` | Acceso a miembros null-safe |\n| Elvis `?:` | Valor por defecto para nullables |\n| `let`\u002F`apply`\u002F`also`\u002F`run`\u002F`with` | Funciones de scope para código limpio |\n| Funciones de extensión | Agregar comportamiento sin herencia |\n| `copy()` | Actualizaciones inmutables en data classes |\n| `require`\u002F`check` | Aserciones de precondiciones |\n| Coroutine `async`\u002F`await` | Ejecución concurrente estructurada |\n| `Flow` | Streams reactivos fríos |\n| `sequence` | Evaluación diferida |\n| Delegación `by` | Reutilizar implementación sin herencia |\n\n## Anti-Patrones a Evitar\n\n```kotlin\n\u002F\u002F Mal: Desempaquetar forzadamente tipos nullable\nval name = user!!.name\n\n\u002F\u002F Mal: Fuga de tipos de plataforma desde Java\nfun getLength(s: String) = s.length \u002F\u002F Seguro\nfun getLength(s: String?) = s?.length ?: 0 \u002F\u002F Manejar nulls de Java\n\n\u002F\u002F Mal: Data classes mutables\ndata class MutableUser(var name: String, var email: String)\n\n\u002F\u002F Mal: Usar excepciones para control de flujo\ntry {\n    val user = findUser(id)\n} catch (e: NotFoundException) {\n    \u002F\u002F No usar excepciones para casos esperados\n}\n\n\u002F\u002F Bien: Usar retorno nullable o Result\nval user: User? = findUserOrNull(id)\n\n\u002F\u002F Mal: Ignorar el scope de coroutine\nGlobalScope.launch { \u002F* Evitar GlobalScope *\u002F }\n\n\u002F\u002F Bien: Usar concurrencia estructurada\ncoroutineScope {\n    launch { \u002F* Correctamente delimitado *\u002F }\n}\n\n\u002F\u002F Mal: Funciones de scope profundamente anidadas\nuser?.let { u ->\n    u.address?.let { a ->\n        a.city?.let { c -> process(c) }\n    }\n}\n\n\u002F\u002F Bien: Cadena null-safe directa\nuser?.address?.city?.let { process(it) }\n```\n\n**Recuerda**: El código Kotlin debe ser conciso pero legible. Aprovecha el sistema de tipos para seguridad, prefiere la inmutabilidad y usa coroutines para concurrencia. Ante la duda, deja que el compilador te ayude.\n","# Patrones de Desarrollo Kotlin\n\nPatrones idiomáticos de Kotlin y buenas prácticas para construir aplicaciones robustas, eficientes y mantenibles.\n\n## Cuándo Usar\n\n- Escribir nuevo código Kotlin\n- Revisar código Kotlin\n- Refactorizar código Kotlin existente\n- Diseñar módulos o librerías Kotlin\n- Configurar builds con Gradle Kotlin DSL\n\n## Cómo Funciona\n\nEste skill aplica convenciones idiomáticas de Kotlin en siete áreas clave: null safety usando el sistema de tipos y operadores de llamada segura, inmutabilidad mediante `val` y `copy()` en data classes, clases selladas e interfaces para jerarquías de tipos exhaustivas, concurrencia estructurada con coroutines y `Flow`, funciones de extensión para agregar comportamiento sin herencia, builders de DSL type-safe usando `@DslMarker` y receptores lambda, y Gradle Kotlin DSL para configuración de build.\n\n## Ejemplos\n\n**Null safety con el operador Elvis:**\n```kotlin\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n```\n\n**Sealed class para resultados exhaustivos:**\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**Concurrencia estructurada con 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## Principios Fundamentales\n\n### 1. Null Safety\n\nEl sistema de tipos de Kotlin distingue tipos nullable de no-nullable. Aprovecharlo al máximo.\n\n```kotlin\n\u002F\u002F Bien: Usar tipos no-nullable por defecto\nfun getUser(id: String): User {\n    return userRepository.findById(id)\n        ?: throw UserNotFoundException(\"User $id not found\")\n}\n\n\u002F\u002F Bien: Llamadas seguras y operador Elvis\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user?.email ?: \"unknown@example.com\"\n}\n\n\u002F\u002F Mal: Desempaquetar forzadamente tipos nullable\nfun getUserEmail(userId: String): String {\n    val user = userRepository.findById(userId)\n    return user!!.email \u002F\u002F Lanza NPE si es null\n}\n```\n\n### 2. Inmutabilidad por Defecto\n\nPreferir `val` sobre `var`, colecciones inmutables sobre mutables.\n\n```kotlin\n\u002F\u002F Bien: Datos inmutables\ndata class User(\n    val id: String,\n    val name: String,\n    val email: String,\n)\n\n\u002F\u002F Bien: Transformar con copy()\nfun updateEmail(user: User, newEmail: String): User =\n    user.copy(email = newEmail)\n\n\u002F\u002F Bien: Colecciones inmutables\nval users: List\u003CUser> = listOf(user1, user2)\nval filtered = users.filter { it.email.isNotBlank() }\n\n\u002F\u002F Mal: Estado mutable\nvar currentUser: User? = null \u002F\u002F Evitar estado global mutable\nval mutableUsers = mutableListOf\u003CUser>() \u002F\u002F Evitar a menos que sea realmente necesario\n```\n\n### 3. Cuerpos de Expresión y Funciones de Una Sola Expresión\n\nUsar cuerpos de expresión para funciones concisas y legibles.\n\n```kotlin\n\u002F\u002F Bien: Cuerpo de expresión\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 Bien: When como expresión\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 Mal: Cuerpo de bloque innecesario\nfun isAdult(age: Int): Boolean {\n    return age >= 18\n}\n```\n\n### 4. Data Classes para Objetos de Valor\n\nUsar data classes para tipos que principalmente contienen datos.\n\n```kotlin\n\u002F\u002F Bien: Data class con 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 Bien: Value class para type safety (cero overhead en tiempo de ejecución)\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## Clases Selladas e Interfaces\n\n### Modelar Jerarquías Restringidas\n\n```kotlin\n\u002F\u002F Bien: Sealed class para when exhaustivo\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### Sealed Interfaces para Respuestas de 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## Funciones de Scope\n\n### Cuándo Usar Cada Una\n\n```kotlin\n\u002F\u002F let: Transformar resultado nullable o delimitado\nval length: Int? = name?.let { it.trim().length }\n\n\u002F\u002F apply: Configurar un objeto (retorna el objeto)\nval user = User().apply {\n    name = \"Alice\"\n    email = \"alice@example.com\"\n}\n\n\u002F\u002F also: Efectos secundarios (retorna el objeto)\nval user = createUser(request).also { logger.info(\"Created user: ${it.id}\") }\n\n\u002F\u002F run: Ejecutar un bloque con receptor (retorna resultado)\nval result = connection.run {\n    prepareStatement(sql)\n    executeQuery()\n}\n\n\u002F\u002F with: Forma no-extensión de run\nval csv = with(StringBuilder()) {\n    appendLine(\"name,email\")\n    users.forEach { appendLine(\"${it.name},${it.email}\") }\n    toString()\n}\n```\n\n### Anti-Patrones\n\n```kotlin\n\u002F\u002F Mal: Anidar funciones de scope\nuser?.let { u ->\n    u.address?.let { addr ->\n        addr.city?.let { city ->\n            println(city) \u002F\u002F Difícil de leer\n        }\n    }\n}\n\n\u002F\u002F Bien: Encadenar llamadas seguras en su lugar\nval city = user?.address?.city\ncity?.let { println(it) }\n```\n\n## Funciones de Extensión\n\n### Agregar Funcionalidad Sin Herencia\n\n```kotlin\n\u002F\u002F Bien: Extensiones específicas del dominio\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 Bien: Extensiones de colecciones\nfun \u003CT> List\u003CT>.second(): T = this[1]\n\nfun \u003CT> List\u003CT>.secondOrNull(): T? = getOrNull(1)\n\n\u002F\u002F Bien: Extensiones delimitadas (sin contaminar el namespace global)\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## Coroutines\n\n### Concurrencia Estructurada\n\n```kotlin\n\u002F\u002F Bien: Concurrencia estructurada con 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 Bien: supervisorScope cuando los hijos pueden fallar independientemente\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 para Streams Reactivos\n\n```kotlin\n\u002F\u002F Bien: Flow frío con manejo de errores adecuado\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 Bien: Operadores de 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### Cancelación y Limpieza\n\n```kotlin\n\u002F\u002F Bien: Respetar la cancelación\nsuspend fun processItems(items: List\u003CItem>) {\n    items.forEach { item ->\n        ensureActive() \u002F\u002F Verificar cancelación antes del trabajo costoso\n        processItem(item)\n    }\n}\n\n\u002F\u002F Bien: Limpieza con try\u002Ffinally\nsuspend fun acquireAndProcess() {\n    val resource = acquireResource()\n    try {\n        resource.process()\n    } finally {\n        withContext(NonCancellable) {\n            resource.release() \u002F\u002F Siempre liberar, incluso al cancelar\n        }\n    }\n}\n```\n\n## Delegación\n\n### Delegación de Propiedades\n\n```kotlin\n\u002F\u002F Inicialización diferida\nval expensiveData: List\u003CUser> by lazy {\n    userRepository.findAll()\n}\n\n\u002F\u002F Propiedad observable\nvar name: String by Delegates.observable(\"initial\") { _, old, new ->\n    logger.info(\"Name changed from '$old' to '$new'\")\n}\n\n\u002F\u002F Propiedades respaldadas por Map\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### Delegación de Interfaces\n\n```kotlin\n\u002F\u002F Bien: Delegar implementación de interfaz\nclass LoggingUserRepository(\n    private val delegate: UserRepository,\n    private val logger: Logger,\n) : UserRepository by delegate {\n    \u002F\u002F Solo sobreescribir lo que necesitas agregar logging\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## Builders de DSL\n\n### Builders Type-Safe\n\n```kotlin\n\u002F\u002F Bien: DSL con @DslMarker\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 Uso\nval page = html {\n    head { title(\"My Page\") }\n    body {\n        h1(\"Welcome\")\n        p(\"Hello, World!\")\n    }\n}\n```\n\n### DSL de Configuración\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 Uso\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## Secuencias para Evaluación Diferida\n\n```kotlin\n\u002F\u002F Bien: Usar secuencias para colecciones grandes con múltiples operaciones\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 Bien: Generar secuencias infinitas\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### Configuración de build.gradle.kts\n\n```kotlin\n\u002F\u002F Verificar las últimas versiones: 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 Coroutines\n    implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2\")\n\n    \u002F\u002F Pruebas\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## Patrones de Manejo de Errores\n\n### Tipo Result para Operaciones de Dominio\n\n```kotlin\n\u002F\u002F Bien: Usar Result de Kotlin o una sealed class personalizada\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 Bien: Encadenar resultados\nval displayName = createUser(request)\n    .map { it.name }\n    .getOrElse { \"Unknown\" }\n```\n\n### require, check, error\n\n```kotlin\n\u002F\u002F Bien: Precondiciones con mensajes claros\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## Operaciones de Colecciones\n\n### Procesamiento Idiomático de Colecciones\n\n```kotlin\n\u002F\u002F Bien: Operaciones encadenadas\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 Bien: Agrupación y agregación\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 Bien: Associate para creación de maps\nval usersById: Map\u003CUserId, User> = users.associateBy { it.id }\n\n\u002F\u002F Bien: Partition para dividir\nval (active, inactive) = users.partition { it.isActive }\n```\n\n## Referencia Rápida: Modismos de Kotlin\n\n| Modismo | Descripción |\n|---------|-------------|\n| `val` sobre `var` | Preferir variables inmutables |\n| `data class` | Para objetos de valor con equals\u002FhashCode\u002Fcopy |\n| `sealed class\u002Finterface` | Para jerarquías de tipos restringidas |\n| `value class` | Para wrappers type-safe con cero overhead |\n| `when` expresión | Pattern matching exhaustivo |\n| Llamada segura `?.` | Acceso a miembros null-safe |\n| Elvis `?:` | Valor por defecto para nullables |\n| `let`\u002F`apply`\u002F`also`\u002F`run`\u002F`with` | Funciones de scope para código limpio |\n| Funciones de extensión | Agregar comportamiento sin herencia |\n| `copy()` | Actualizaciones inmutables en data classes |\n| `require`\u002F`check` | Aserciones de precondiciones |\n| Coroutine `async`\u002F`await` | Ejecución concurrente estructurada |\n| `Flow` | Streams reactivos fríos |\n| `sequence` | Evaluación diferida |\n| Delegación `by` | Reutilizar implementación sin herencia |\n\n## Anti-Patrones a Evitar\n\n```kotlin\n\u002F\u002F Mal: Desempaquetar forzadamente tipos nullable\nval name = user!!.name\n\n\u002F\u002F Mal: Fuga de tipos de plataforma desde Java\nfun getLength(s: String) = s.length \u002F\u002F Seguro\nfun getLength(s: String?) = s?.length ?: 0 \u002F\u002F Manejar nulls de Java\n\n\u002F\u002F Mal: Data classes mutables\ndata class MutableUser(var name: String, var email: String)\n\n\u002F\u002F Mal: Usar excepciones para control de flujo\ntry {\n    val user = findUser(id)\n} catch (e: NotFoundException) {\n    \u002F\u002F No usar excepciones para casos esperados\n}\n\n\u002F\u002F Bien: Usar retorno nullable o Result\nval user: User? = findUserOrNull(id)\n\n\u002F\u002F Mal: Ignorar el scope de coroutine\nGlobalScope.launch { \u002F* Evitar GlobalScope *\u002F }\n\n\u002F\u002F Bien: Usar concurrencia estructurada\ncoroutineScope {\n    launch { \u002F* Correctamente delimitado *\u002F }\n}\n\n\u002F\u002F Mal: Funciones de scope profundamente anidadas\nuser?.let { u ->\n    u.address?.let { a ->\n        a.city?.let { c -> process(c) }\n    }\n}\n\n\u002F\u002F Bien: Cadena null-safe directa\nuser?.address?.city?.let { process(it) }\n```\n\n**Recuerda**: El código Kotlin debe ser conciso pero legible. Aprovecha el sistema de tipos para seguridad, prefiere la inmutabilidad y usa coroutines para concurrencia. Ante la duda, deja que el compilador te ayude.\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fes\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\u002Fes\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",[],[]]