Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 134 ยท Idiomatic Kotlin

Type-Safe Builders and DSLs

Build your own Kotlin DSL: lambdas with receivers, nested builders, operator tricks and @DslMarker, with an HTML builder, a config DSL and the real compiler errors.

Look at this Kotlin code: html { body { p { +"Hello" } } }. It looks like a markup language, yet it is ordinary Kotlin: every brace is a lambda and every name is a function call. A domain-specific language (DSL) is a small, focused vocabulary built on top of a general-purpose language. In Kotlin you can build one with plain functions, and the compiler still checks every word. Gradle build scripts (build.gradle.kts), Jetpack Compose, Ktor routing and kotlinx.html all use this technique.

The ingredient behind all of it is the lambda with receiver. Once you understand that, builders are just a pattern. This lesson starts from the one idea, builds a small HTML DSL and a configuration DSL, shows the classic scoping bug and its cure, @DslMarker, and ends with advice about when a DSL is worth writing. You should be comfortable with lambdas, extension functions and function types.

The key idea: a lambda with receiver

An ordinary lambda (String) -> Unit receives a value as a parameter. A lambda with receiver, written String.() -> Unit, runs as if it were an extension function of String: inside the braces this is a String, and you can call its members without a prefix. You already know the standard-library examples: apply, with, run and buildString are all functions that take a lambda with receiver (see Scope Functions).

Kotlin Writing your own buildString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The call sb.block() is the whole trick. The caller of makeGreeting writes calls like append("Hello") with no sb. in front, because the lambda's receiver is a StringBuilder. The function that takes the lambda decides what the receiver is, so it decides which words are available in the block. That is how a DSL controls its own vocabulary.

A lambda with receiver is only a convenience for the reader. It does not give extra access: private members of the receiver stay private. Inside the block you can still use variables from the surrounding code, because lambdas capture them.

A builder pattern in four steps

A type-safe builder is a set of classes plus functions that take lambdas with receivers. The recipe has four steps:

  1. A class represents each node of the structure (a tag, a section, a request).
  2. A function such as html { ... } creates the root, runs the user's lambda on it and returns it.
  3. The same helper is used for children: it creates a child object, runs the lambda on it, then stores the child in its parent.
  4. Because every lambda has the right receiver, the editor and the compiler only offer words that make sense at that level.

Here is a small HTML builder. The classes are tiny; the interesting part is initTag, which is the repeated pattern.

Kotlin A tiny HTML DSL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Walk through html { body { p { +"..." } } } step by step:

  • html creates an Html and runs the outer lambda with that Html as this. Inside, the name body resolves to Html.body.
  • body { ... } creates a Body, runs the next lambda with it as receiver, so p and ul now resolve to Body members.
  • Inside p { ... } the receiver is a P. The line +"text" is "text".unaryPlus(), a member extension declared inside P, which is why it works only there. Writing +"x" directly inside body { } would not compile.

The structure is type-safe: li exists only on Ul, html cannot be nested in a p, and a misspelled tag is a compile error, not a broken page found later. That is the advantage over building the same output from strings. This is a model of the idea, not an HTML library; real code must also escape the text so that < and & do not break the markup.

The member extension operator fun String.unaryPlus() is a compact way to add text. It is a style choice that kotlinx.html also uses. A plain text("...") function is just as valid and easier to discover.

The scoping problem, and @DslMarker

Here is a flaw in the builder above. Inside a lambda, all enclosing receivers are available at once. Kotlin searches this first, then the receiver one level out, and so on. So inside li { ... } you could call li again, because Ul.li is reachable through the outer receiver, and the nesting would silently produce nonsense. Let us see it with a smaller example, where item belongs to Group and group belongs to Root:

Kotlin An outer receiver leaks into an inner block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

It compiles and runs and prints item and then 2: the stray group inside item attaches a second group to the outer Root. For a real HTML DSL that means a <p> inside <li> attaching to the wrong parent. The fix is the annotation @DslMarker. You define your own annotation, mark it with @DslMarker, and put it on the classes of the DSL. The rule then becomes: within one DSL, an implicit receiver may only call members of the innermost receiver of that DSL. To reach an outer one you must say so explicitly with this@Name.

Kotlin @DslMarker blocks implicit outer calls (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler now rejects the inner group call: main.kt:25:17: error: 'fun group(init: Group.() -> Unit): Unit' cannot be called in this context with an implicit receiver. Use an explicit receiver if necessary. The annotation does not forbid reaching the outer receiver, it only forces you to write it down, which makes the intent visible. Remove the inner group and the code compiles. The same applies to html DSLs: put @HtmlDsl on every node class and the compiler prevents li inside li.

Kotlin The explicit this@ escape hatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

this@group names the receiver of the lambda passed to group (the label comes from the function name). Explicit labels always work; only the implicit lookup is restricted.

Beyond tags: a configuration DSL

HTML is the textbook example, but DSLs shine for configuration, tests, routes and queries. This one describes a small server and collects values into a result. The builder classes are mutable and private to the DSL; the finished result is an immutable data class.

Kotlin A configuration DSL with defaults and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice three design choices that make the DSL pleasant:

  • Properties for single values (host = "...", port = 9000) and functions for nested blocks (routes { }). That mirrors how people think about configuration.
  • Defaults live in the builder, so an empty block is a valid configuration.
  • build() validates and returns an immutable value. The mutable builder never escapes, so code that receives a ServerConfig can trust it. Validation with require is covered in require, check and assert.

The standard-library builders

The standard library ships builders you should use before writing your own. They are all functions taking a lambda with receiver, and they let you keep the mutable collection inside the block:

Kotlin buildString, buildList and buildMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Inside buildList, this is a MutableList<T>; the result is returned as a read-only List. These builders are inline functions, so there is no runtime cost for the lambda itself. See Inline Functions.

A DSL with a function type as an argument

Receivers can also be combined with ordinary parameters. A builder may take both a name and a block, and it can store the lambda itself to run later. This is how test DSLs (test("name") { ... }) and route tables work:

Kotlin Storing lambdas with receivers for later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The map stores values of the function type Checks.() -> Unit, which you call as checks.body() or body(checks); both are legal because the receiver is just the first parameter.

Design advice and pitfalls

  • Start without a DSL. A DSL is worth it when there is nested structure or many optional settings. For three parameters, a function with default and named arguments is simpler.
  • Keep the vocabulary small and consistent. Users must guess names: prefer get/post over addGetRoute.
  • Always add @DslMarker when blocks nest. Without it, mistakes compile and attach to the wrong parent.
  • Separate builder from result. Mutable builders are fine inside; hand out immutable values.
  • Remember errors surface at run time for rules the type system cannot express (a required field left empty). Validate in build() and give clear messages.
  • Mind the cost. Every block is a lambda object unless the function is inline. For hot paths, make the building functions inline; for configuration code it does not matter.
  • Avoid hiding side effects. A function that looks like markup but secretly opens files will surprise people.
  • Debuggability: stack traces show many nested lambdas. Keep builder functions short so the trace stays readable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is this inside a lambda of type StringBuilder.() -> Unit?

    A lambda with receiver behaves like an extension function: this is the receiver object, so you can call its members without a prefix.
  2. 2. In an HTML builder, what does +"text" inside p { } compile to?

    The unary plus operator maps to unaryPlus(). A member extension declared inside P is only available while P is the receiver.
  3. 3. What problem does @DslMarker solve?

    Without the marker, the members of every enclosing receiver are reachable, so mistakes such as li inside li compile. With the marker only the innermost receiver of the DSL is implicit; outer ones need this@label.
  4. 4. Why should a builder usually return an immutable result from build()?

    The mutable builder is an implementation detail. The validated immutable value is what the rest of the program sees.
  5. 5. How do you call a stored value body of type Checks.() -> Unit on a checks object?

    A function type with receiver can be called with the receiver in front of the call or passed as the first argument.

Summary

  • A lambda with receiver (T.() -> Unit) runs with this set to a T; the function that takes it chooses the vocabulary.
  • A type-safe builder is classes plus functions that create a child, run the lambda on it, and attach it to the parent.
  • Member extensions such as operator fun String.unaryPlus() give a DSL its text syntax.
  • Without @DslMarker, outer receivers leak into inner blocks; with it, you must write this@label.
  • Keep mutable builders internal, validate in build(), and return immutable values.
  • Prefer buildString, buildList and buildMap from the standard library when they are enough.
  • Write a DSL only when nested structure makes plain functions awkward.

Next: Operator Conventions