DSL Construction in Kotlin

From the Kotlin cheat sheet · DSL Building · verified Jul 2026

DSL Construction

Building type-safe DSLs

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

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

class Body : Element() {
    fun h1(text: String, init: H1.() -> Unit = {}) {
        val h1 = H1(text)
        h1.init()
        children.add(h1)
    }

    fun p(text: String) {
        children.add(P(text))
    }
}

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

// Usage
val doc = html {
    body {
        h1("Title") {
            // H1 configuration
        }
        p("Paragraph text")
    }
}
💡 Lambda with receiver enables DSL syntax
⚡ @DslMarker prevents scope leaking in nested DSLs
📌 Infix functions create natural language-like APIs
🟢 Type-safe builders provide compile-time validation
Back to the full Kotlin cheat sheet