Search code examples
lambdakotlindslreceiver

"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")
    }
}

Solution

  • 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.