Explanation of a function literal with a sink in Kotlin

I followed this link https://kotlin.link/articles/DSL-builder-in-Kotlin.html to understand the builder implementation in Kotlin. I didn't understand the methods inside the Builder class. The method name()

takes an extension function as an argument that receives nothing and returns a String. And the caller calls name { "ABC" }

. If the caller passes a String to a method name

, how is it converted to an extension method that returns a String?

I tried following the Kotlin documentation for function literals with receivers, but all had samples that return Unit

or reference DSL Builders. Tried to ruin him to understand, but no luck in understanding the concept.

+3


source to share


1 answer


The call name { "ABC" }

is a combination of two Kotlin conventions.

There is a convention that if the last parameter of a function is a function, you can omit the parentheses. Also, since there are no parameters for the lambda, "ABC"

this is what is returned by it.



Thus, the caller is actually passing the lambda in a form name ({() -> "ABC"})

, not a String.

Looking at the example in the link it doesn't sound like what the receiver is needed for name()

, so it can be confusing.

+5


source







All Articles