Kotlin

Type-Safe Builder DSL

admin by @admin ADMIN
10m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`@DslMarker` + lambdas with receivers let you build statically-typed DSLs that look like declarative configuration. The HTML / Gradle Kotlin DSL style.
Kotlin
Raw
@DslMarker annotation class HtmlDsl

@HtmlDsl
class Tag(val name: String) {
    val children = mutableListOf<Tag>()
    val attributes = mutableMapOf<String, String>()
    var text: String? = null

    fun render(): String = buildString {
        append("<$name")
        attributes.forEach { (k, v) -> append(" $k=\"$v\"") }
        append(">")
        text?.let { append(it) }
        children.forEach { append(it.render()) }
        append("</$name>")
    }
}

fun html(block: Tag.() -> Unit): Tag = Tag("html").apply(block)
fun Tag.body(block: Tag.() -> Unit): Tag = Tag("body").apply(block).also { children.add(it) }
fun Tag.h1(text: String) { children += Tag("h1").apply { this.text = text } }
fun Tag.p(text: String)  { children += Tag("p").apply  { this.text = text } }

fun main() {
    val page = html {
        body {
            h1("Hello, world")
            p("Welcome to my page.")
        }
    }
    println(page.render())
    // <html><body><h1>Hello, world</h1><p>Welcome to my page.</p></body></html>
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.