Claude
Skills
Sign in
Back

Kotlin DSL Patterns

Included with Lifetime
$97 forever

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.

Design

What this skill does


# 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.

```kotlin
// 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.

```kotlin
// 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("World")
}

// Extension functions as DSL builders
class Query {
    private val conditions = mutableListOf<String>()

    fun where(condition: String) {
        conditions.add(condition)
    }

    fun build(): String {
        return "SELECT * WHERE ${conditions.joinToString(" AND ")}"
    }
}

fun query(init: Query.() -> Unit): String {
    val query = Query()
    query.init()
    return query.build()
}

val sql = query {
    where("age > 18")
    where("status = 'active'")
}

// Scoped builders
class TestSuite(val name: String) {
    private val tests = mutableListOf<Test>()

    fun test(name: String, block: TestContext.() -> Unit) {
        val context = TestContext()
        context.block()
        tests.add(Test(name, context))
    }

    fun run() {
        println("Running suite: $name")
        tests.forEach { it.run() }
    }
}

class TestContext {
    val assertions = mutableListOf<() -> Unit>()

    fun assertEquals(expected: Any, actual: Any) {
        assertions.add {
            if (expected != actual) {
                throw AssertionError("Expected $expected but got $actual")
            }
        }
    }
}

class Test(val name: String, val context: TestContext) {
    fun run() {
        println("  Test: $name")
        context.assertions.forEach { it() }
    }
}

fun suite(name: String, init: TestSuite.() -> Unit): TestSuite {
    val suite = TestSuite(name)
    suite.init()
    return suite
}

// Using test DSL
val testSuite = suite("Math Tests") {
    test("addition") {
        assertEquals(4, 2 + 2)
        assertEquals(0, 1 - 1)
    }

    test("multiplication") {
        assertEquals(6, 2 * 3)
    }
}

// Apply and also for DSL chaining
data class Person(
    var name: String = "",
    var age: Int = 0,
    var email: String = ""
)

fun createPerson() = Person().apply {
    name = "Alice"
    age = 30
    email = "[email protected]"
}

// With for scoped access
fun processConfig(config: ServerConfig) {
    with(config) {
        println("Server on $host:$port")
        routes.forEach { route ->
            println("  ${route.method} ${route.path}")
        }
    }
}
```

Lambdas with receivers enable accessing receiver members without explicit
qualifiers, creating natural, context-aware DSL syntax.

## Infix Functions and Operators

Infix functions and operator overloading enable natural mathematical and logical
expressions in DSLs, improving readability for domain concepts.

```kotlin
// Infix functions for fluent API
infix fun String.shouldEqual(expected: String) {
    if (this != expected) {
        throw AssertionError("Expected '$expected' but got '$this'")
    }
}

"hello" shouldEqual "hello"

// Time duration DSL with infix
class Duration(val milliseconds: Long) {
    operator fun plus(other: Duration) =
        Duration(milliseconds + other.milliseconds)

    override fun toString() = "${milliseconds}ms"
}

infix fun Int.seconds(unit: Unit) = Duration(this * 1000L)
infix fun Int.minutes(unit: Unit) = Duration(this 

Related in Design