Building a Type-Safe HTML/Config DSL
Implement a simple configuration DSL using builder patterns and extension lambdas.
Building a Type-Safe HTML/Config DSL is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Goal: A Practical DSL
We will build a minimal but realistic HTML builder DSL in Kotlin. The same patterns apply to any config, test fixture, or report builder. The result is a typesafe, IDE-friendly API that replaces string concatenation.
Define the Tag Base Class
All HTML elements share a common shape: a name, attributes, and children. Start with a base class:
open class Tag(val name: String) {
val attrs = mutableMapOf<String, String>()
val children = mutableListOf<Tag>()
fun render(indent: Int = 0): String {
val pad = " ".repeat(indent)
val attrStr = if (attrs.isEmpty()) "" else " " + attrs.entries.joinToString(" ") { "${it.key}=\"${it.value}\"" }
val body = children.joinToString("\n") { it.render(indent + 2) }
return "$pad<$name$attrStr>\n$body\n$pad</$name>"
}
}Apply @DslMarker
Mark all builder classes so inner scopes cannot accidentally call outer-scope methods:
@DslMarker
annotation class HtmlDsl
@HtmlDsl class Html : Tag("html")
@HtmlDsl class Head : Tag("head")
@HtmlDsl class Body : Tag("body")
@HtmlDsl class Div : Tag("div")
@HtmlDsl class P : Tag("p")Add Builder Functions
Each tag class gets an extension function that creates a child tag, applies the block, and adds it to children:
fun Html.head(block: Head.() -> Unit) = Head().also { it.block(); children += it }
fun Html.body(block: Body.() -> Unit) = Body().also { it.block(); children += it }
fun Body.div(block: Div.() -> Unit) = Div().also { it.block(); children += it }
fun Div.p(text: String) = P().also { it.attrs["text"] = text; children += it }Top-Level html Builder
Provide a top-level entry point that creates the root element and applies the user block:
fun html(block: Html.() -> Unit): Html {
val root = Html()
root.block()
return root
}Using the DSL
The result is a clean, readable DSL:
val page = html {
head { }
body {
div {
p("Hello, DSL!")
}
}
}
println(page.render())Adding Attributes
Add an attr helper to set arbitrary attributes fluently:
fun Tag.attr(key: String, value: String) { attrs[key] = value }
// Usage
div {
attr("class", "container")
p("Content")
}Config DSL Pattern
The same pattern works for configuration objects. Instead of HTML tags, use domain classes:
class ServerConfig {
var host = "localhost"
var port = 8080
var db: DbConfig? = null
fun database(block: DbConfig.() -> Unit) { db = DbConfig().apply(block) }
}
fun server(block: ServerConfig.() -> Unit) = ServerConfig().apply(block)Nesting and Composing
Because each builder function returns the created object, you can compose builders freely. The DSL nesting depth matches the data hierarchy depth.
Error Prevention by Types
The type system enforces structure: you cannot call body { } inside a Head because Head has no body extension function. Invalid structures are compile-time errors.
Rendering and Testing
Because the DSL produces a plain Kotlin object tree, rendering and testing are straightforward: call render() and assert on the output string, or walk the object tree in tests.
Extending the DSL Later
Adding new tags or config options only requires new extension functions on the appropriate receiver class. Existing call sites are unaffected — open/closed in practice.
Quick Check
What makes a Kotlin HTML/config DSL "type-safe"?
Recap: Building a Type-Safe DSL
Key steps:
- Define builder classes for each level of the hierarchy
- Annotate with
@DslMarkerto prevent receiver leakage - Write extension functions that create, configure, and add child objects
- Expose a top-level entry-point function
- Rendering and testing work on plain Kotlin objects
Frequently asked questions
Is the “Building a Type-Safe HTML/Config DSL” lesson free?
Yes — the full text of “Building a Type-Safe HTML/Config DSL” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “Building a Type-Safe HTML/Config DSL”?
Implement a simple configuration DSL using builder patterns and extension lambdas. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Building a Type-Safe HTML/Config DSL” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Lambda with Receiver: The DSL Foundation
- @DslMarker: Preventing Receiver Leakage
- Building a Type-Safe HTML/Config DSL
- Testing and Evolving DSLs Without Breaking Users