What is a lambda with a receiver?

What is a lambda with a receiver in Kotlin, and we have extension functions?

The two functions below perform the same things, however the first of them is more readable and short:

fun main(args: Array<String>) {
    println("123".represents(123))
    println(123.represents("123"))
}

fun String.represents(another: Int) = toIntOrNull() == another

val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}
+7
source share
1 answer

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, ..
+18

Source: https://habr.com/ru/post/1689376/


All Articles