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 elements1class HtmlBuilder { // The generated tags, kept private2 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 breaks6 override fun toString() = elements.joinToString("\n")7}8 // HtmlBuilder.() -> Unit: a lambda that runs with an HtmlBuilder as this9fun html(init: HtmlBuilder.() -> Unit): String { // Create the receiver object10 val builder = HtmlBuilder() // Call the lambda on builder, which becomes this inside it11 builder.init() // Return the collected HTML as a string12 return builder.toString()13}14 // DSL-style call with a trailing lambda15val result = html { // Same as this.tag(...): this is the HtmlBuilder16 tag("h1", "Title")17 tag("p", "Hello World")18}// Prints <h1>Title</h1> and <p>Hello World</p> on two lines19println(result)Output
<h1>Title</h1> <p>Hello World</p>
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