liveBook · Manning

Type-safe builder

As explained in Kotlin in Action, 2E

A type-safe builder is a builder API whose structure and allowed operations are checked by the programming language's type system.

A type-safe builder uses Kotlin code to describe an object hierarchy declaratively while the type system restricts which operations are valid in each context. section 13.2.2

Build an HTML table

fun createSimpleTable() = createHTML().table { tr { td { +"cell" } } } Here, table, tr, and td are ordinary functions receiving lambdas with receivers. The table receiver exposes tr, while the tr receiver exposes td; outside those blocks, the names are unresolved. The API therefore enforces the intended HTML grammar. section 13.2.2

Receiver types define the available names in each nested block. A shared Tag superclass can collect children and render them, while a DSL marker prevents confusing access when multiple receivers are in scope.

How Kotlin in Action, 2E covers it

How deep it goes
Explains receiver lambdas, scoped name resolution, tag classes, rendering, and DSL markers through a complete implementation.
Examples
Uses nested HTML table, row, and cell builders, string content, dynamic loops, explicit receivers, and generated HTML output.
What it assumes
Uses ordinary Kotlin functions, higher-order functions, receiver lambdas, and unary-plus operator calls.
What you can do after
Builds Kotlin HTML builders that constrain nesting, collect child tags, and generate HTML strings.
How it connects
Connects lambdas with receivers, higher-order functions, extension lambdas, operator overloading, DSLs, and type systems.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.