<commit_before>---
type: doc
layout: reference
category: "Syntax"
title: "Type-Safe Builders"
---

# Type-Safe Builders

By using well-named functions as builders in combination with extension lambdas it is possible to create static type safe builders in Kotlin. Type-safe builders are also known as domain specific languages (DSLs).

Builders, or domain specific languages, are a good solution for often-repeated code that builds complex data structures in a semi-declarative way. Builders are good for [generating XML](http://www.groovy-lang.org/processing-xml.html#_creating_xml), 
[laying out UI components](http://www.groovy-lang.org/swing.html), 
[describing 3D scenes](http://www.artima.com/weblogs/viewpost.jsp?thread=296081), and more...

To support builders that can't be statically typed, Kotlin supports also supports [Dynamic types](/docs/reference/dynamic-type.html) builders.

## A type-safe builder example

Consider the following code:

``` kotlin
import com.example.html.* // see declarations below

fun result(args: Array<String>) =
    html {<commit_msg>Update type-safe-builders.md<commit_after>---
type: doc
layout: reference
category: "Syntax"
title: "Type-Safe Builders"
---

# Type-Safe Builders

By using well-named functions as builders in combination with [function literals with receiver](lambdas.html#function-literals-with-receiver) it is possible to create type-safe, statically-typed builders in Kotlin.

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

* Generating markup with Kotlin code, such as [HTML](https://github.com/Kotlin/kotlinx.html) or XML;
* Programmatically laying out UI components: [Anko](https://github.com/Kotlin/anko/wiki/Anko-Layouts)
* Configuring routes for a web server: [Ktor](http://ktor.io/features/routing.html#routing-tree).

## A type-safe builder example

Consider the following code:

``` kotlin
import com.example.html.* // see declarations below

fun result(args: Array<String>) =
    html {
{'fraction_non_alphanumeric': 0.10267229254571027, 'fraction_numerical': 0.0032817627754336614, 'mean_word_length': 4.830601092896175, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 3, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5515002', 'n_tokens_mistral': 634, 'n_tokens_neox': 606, 'n_words': 220}