Introduction
A lambda with receiver lets you write code that feels like it belongs to an object, making your code cleaner and easier to read.
val lambdaName: ReceiverType.() -> ReturnType = { // code using 'this' as ReceiverType }
val greet: String.() -> String = { "Hello, $this!" } val message = "World".greet()
val addExclamation: StringBuilder.() -> Unit = { append("!") } val sb = StringBuilder("Hi") sb.addExclamation()
fun main() { val buildMessage: StringBuilder.() -> Unit = { append("Hello") append(", ") append("Kotlin") append("!") } val messageBuilder = StringBuilder() messageBuilder.buildMessage() println(messageBuilder.toString()) }
lambda with receiver in Kotlin?StringBuilder in Kotlin?StringBuilder.() -> Unit.append("Hello") inside the lambda, which is valid for StringBuilder.val buildString: StringBuilder.() -> Unit = {
append("Hi")
append(", ")
append("there!")
}
val result = StringBuilder().apply(buildString).toString()
println(result)buildString is a StringBuilder receiver lambda that appends "Hi", ", ", and "there!" to the StringBuilder.apply function runs the lambda on a new StringBuilder instance, then toString() converts it to the string "Hi, there!".val printLength: String.() -> Unit = {
println(length())
}
"Hello".printLength()length is a property of String, not a function, so calling length() causes an error.String as receiver and returns Unit, and calling printLength without parentheses is valid syntax.buildHtml that uses a lambda with receiver to build an HTML string with nested tags. Which approach correctly uses lambda with receiver to achieve this?fun buildHtml(block: StringBuilder.() -> Unit): String {
val sb = StringBuilder()
sb.block()
return sb.toString()
}
val html = buildHtml {
append("")
append("")
append("Hello")
append("")
append("")
}
println(html)buildHtml takes a lambda with receiver StringBuilder.() -> Unit and calls it on sb using sb.block(), which is correct syntax.StringBuilder, and the function returns the built string with sb.toString(), which is the expected behavior.Pass the test and this pattern moves unknown