Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Lambda with Receiver": What is this Kotlin construct?

I'm looking at this Kotlin object declaration:

object A : B({
    variableName1 = "text1"
    variableName2 = "text2"

    params {
        param("Foo", "Bar")
    }
})

And I cannot figure out what the argument to class B's constructor is.

I have purposefully abstracted away information in this example but class B is actually

jetbrains.buildServer.configs.kotlin.v10.BuildType

And I cannot find the documentation for the type. I have found something that was close but it's a definition for an interface and thus doesn't have a constructor.

To summarise, what is this the following construct in Kotlin?

{
    variableName1 = "text1"
    variableName2 = "text2"

    params {
        param("Foo", "Bar")
    }
}
like image 510
ZoSal Avatar asked Oct 12 '17 09:10

ZoSal


People also ask

What is lambda receiver in Kotlin?

Lambda with Receivers Basically, we're pretending that each unqualified function call is using the “Baeldung” string as the receiver of the call. This makes the lambda body more concise. As it turns out, this form of the lambda expression is actually possible in Kotlin by lambda with receivers.

What is receiver type in Kotlin?

It's called a receiver because you can think of the function call as sending a request which the object will receive. Not all functions have a receiver. For example, Kotlin's println() function is a top-level function. When you write: println("Hello, World!")

What is Lamda function in Kotlin?

Lambda is a function which has no name. Lambda is defined with a curly braces {} which takes variable as a parameter (if any) and body of function. The body of function is written after variable (if any) followed by -> operator.

Does lambda support Kotlin?

AWS Lambda does not support serializing JSON objects into Kotlin data classes, but don't worry! AWS Lambda supports passing an input object as a Stream, and also supports an output Stream for returning a result (see this link for more information).


1 Answers

This construct is called "Lambda with Receiver", aka "Function Literal with Receiver", which you'll find used in Kotlin DSL implementations extensively. For an example, have a look at the HTML builder DSL.

I described the whole concept in detail in this thread.

like image 80
s1m0nw1 Avatar answered Dec 28 '22 10:12

s1m0nw1