Type-safe builders

Edit pageLast modified: 10 February 2025

By using well-named functions as builders in combination with function literals with receiver it is possible to create type-safe, statically-typed builders in Kotlin.

Type-safe builders allow creating Kotlin-based domain-specific languages (DSLs) suitable for building complex hierarchical data structures in a semi-declarative way. Sample use cases for the builders are:

  • Generating markup with Kotlin code, such as HTML or XML

  • Configuring routes for a web server: Ktor

Consider the following code:

This is completely legitimate Kotlin code. You can play with this code online (modify it and run in the browser) here.