Lambda with receiver in Kotlin

Level 5408 keystrokes

The parameter type HtmlBuilder.() -> Unit is a lambda with receiver: inside the lambda, this is an HtmlBuilder, so tag() can be called directly. This is how Kotlin DSLs such as HTML builders are written.

Kotlin code

// A builder that collects HTML elements
1class HtmlBuilder {
// The generated tags, kept private
2 private val elements = mutableListOf<String>()
// Adds one element such as <h1>Title</h1>
3 fun tag(name: String, content: String) {
4 elements.add("<$name>$content</$name>")
5 }
// Joins the elements with line breaks
6 override fun toString() = elements.joinToString("\n")
7}
8
// HtmlBuilder.() -> Unit: a lambda that runs with an HtmlBuilder as this
9fun html(init: HtmlBuilder.() -> Unit): String {
// Create the receiver object
10 val builder = HtmlBuilder()
// Call the lambda on builder, which becomes this inside it
11 builder.init()
// Return the collected HTML as a string
12 return builder.toString()
13}
14
// DSL-style call with a trailing lambda
15val result = html {
// Same as this.tag(...): this is the HtmlBuilder
16 tag("h1", "Title")
17 tag("p", "Hello World")
18}
// Prints <h1>Title</h1> and <p>Hello World</p> on two lines
19println(result)

Output

<h1>Title</h1>
<p>Hello World</p>
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 13
  • )× 13
  • "× 12
  • .× 5
  • :× 4
  • {× 4
  • }× 4
  • =× 4
  • >× 4
  • ,× 3

More Kotlin examples at level 5

← Kotlin typing practice