Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Kotlin DSL Patterns

БесплатноБез исполняемых скриптовНе проверен

Use when domain-specific language design in Kotlin using type-safe builders, infix functions, operator overloading, lambdas with receivers, and patterns for…

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Kotlin DSL Patterns

Introduction

Kotlin's language features enable creation of expressive domain-specific languages (DSLs) that feel like natural extensions of the language itself. DSLs improve code readability, reduce boilerplate, and provide type-safe APIs for configuration, builders, and domain modeling.

Key features supporting DSL design include lambdas with receivers, extension functions, infix notation, operator overloading, and scope control. These features combine to create fluent, intuitive APIs that express domain concepts clearly without sacrificing type safety or IDE support.

This skill covers type-safe builders, lambda receivers, infix functions, operator overloading, and practical patterns for designing maintainable DSLs in Android, testing, and configuration contexts.

Type-Safe Builders

Type-safe builders use lambdas with receivers to create hierarchical structures with compile-time validation and IDE support.

// HTML DSL example
class HTML {
    private val elements = mutableListOf<Element>()

    fun head(init: Head.() -> Unit) {
        val head = Head()
        head.init()
        elements.add(head)
    }

    fun body(init: Body.() -> Unit) {
        val body = Body()
        body.init()
        elements.add(body)
    }

    override fun toString(): String {
        return "<html>\n${elements.joinToString("\n")}\n</html>"
    }
}

abstract class Element(val name: String) {
    private val children = mutableListOf<Element>()

    protected fun <T : Element> initElement(element: T, init: T.() -> Unit): T {
        element.init()
        children.add(element)
        return element
    }

    override fun toString(): String {
        return if (children.isEmpty()) {
            "<$name/>"
        } else {
            "<$name>\n${children.joinToString("\n")}\n</$name>"
        }
    }
}

class Head : Element("head") {
    fun title(text: String) {
        initElement(Title()) { this.text = text }
    }
}

class Title : Element("title") {
    var text: String = ""

    override fun toString() = "<title>$text</title>"
}

class Body : Element("body") {
    fun h1(text: String) {
        initElement(H1()) { this.text = text }
    }

    fun p(text: String) {
        initElement(P()) { this.text = text }
    }

    fun div(cssClass: String = "", init: Div.() -> Unit) {
        initElement(Div(cssClass), init)
    }
}

class H1 : Element("h1") {
    var text: String = ""
    override fun toString() = "<h1>$text</h1>"
}

class P : Element("p") {
    var text: String = ""
    override fun toString() = "<p>$text</p>"
}

class Div(private val cssClass: String = "") : Element("div") {
    fun p(text: String) {
        initElement(P()) { this.text = text }
    }

    override fun toString(): String {
        val classAttr = if (cssClass.isNotEmpty()) " class=\"$cssClass\"" else ""
        return "<div$classAttr>...</div>"
    }
}

// Using the HTML DSL
fun buildPage() = html {
    head {
        title("My Page")
    }
    body {
        h1("Welcome")
        p("This is a paragraph")
        div("container") {
            p("Nested paragraph")
        }
    }
}

fun html(init: HTML.() -> Unit): HTML {
    val html = HTML()
    html.init()
    return html
}

// Configuration DSL
class ServerConfig {
    var port: Int = 8080
    var host: String = "localhost"
    val routes = mutableListOf<Route>()

    fun route(path: String, init: Route.() -> Unit) {
        val route = Route(path)
        route.init()
        routes.add(route)
    }
}

class Route(val path: String) {
    var method: String = "GET"
    var handler: (Request) -> Response = { Response(200, "OK") }

    fun get(handler: (Request) -> Response) {
        this.method = "GET"
        this.handler = handler
    }

    fun post(handler: (Request) -> Response) {
        this.method = "POST"
        this.handler = handler
    }
}

data class Request(val path: String, val body: String = "")
data class Response(val status: Int, val body: String)

fun server(init: ServerConfig.() -> Unit): ServerConfig {
    val config = ServerConfig()
    config.init()
    return config
}

// Using configuration DSL
val config = server {
    port = 9000
    host = "0.0.0.0"

    route("/api/users") {
        get { request ->
            Response(200, "User list")
        }
    }

    route("/api/posts") {
        post { request ->
            Response(201, "Post created")
        }
    }
}

Type-safe builders provide IDE autocompletion and compile-time validation while creating readable, hierarchical structures.

Lambdas with Receivers

Lambdas with receivers enable DSL functions to access receiver properties and methods directly, creating implicit context for cleaner APIs.

// Lambda with receiver basics
fun buildString(action: StringBuilder.() -> Unit): String {
    val builder = StringBuilder()
    builder.action()
    return builder.toString()
}

val result = buildString {
    append("Hello")
    append(" ")
    append("W
Полный SKILL.md на GitHub

Установить Kotlin DSL Patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Kotlin DSL Patterns?

Use when domain-specific language design in Kotlin using type-safe builders, infix functions, operator overloading, lambdas with receivers, and patterns for creating expressive, readable DSLs for configuration and domain modeling.

Как установить скилл Kotlin DSL Patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Kotlin DSL Patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

Сравнить Kotlin DSL Patterns с