Lambdas with receivers are basically the same as extension functions; they simply can be stored in properties and passed to functions. This question is essentially the same as "What is the purpose of the lambda when we have functions?". The answer is almost the same - it allows you to quickly create anonymous extension functions anywhere in your code.
There are many good use cases for this (see DSL in particular ), but I will give one simple example here.
, , :
fun buildString(actions: StringBuilder.() -> Unit): String {
val builder = StringBuilder()
builder.actions()
return builder.toString()
}
:
val str = buildString {
append("Hello")
append(" ")
append("world")
}
:
- ,
buildString
, , , . StringBuilder
. StringBuilder
, - .- , , , ,
StringBuilder
- StringBuilder
, ..