简体   繁体   中英

Explanation on Function literal with receiver in Kotlin

I was following 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 Builder class. Method name() receives Extension Function as an argument which receives nothing and returns String. And the caller calls name { "ABC" } . If the caller is passing String to name method, how does it translate to an Extension method which returns String ?

I tried following Kotlin documentation for Function literals with receivers but all had samples which returns Unit or refers to DSL Builders. Tried googling it as well to understand but no luck in grasping the concept.

The call to name { "ABC" } is a combination of two Kotlin conventions.

There is a convention that if the last parameter to a function is a function you can omit the parenthesis. Also since there are no parameters to the lambda, "ABC" is what is returned by it.

So the caller is actually passing a lambda in the form name ({() -> "ABC"}) , rather than a String.

Looking at the example in the link, it doesn't look like the receiver is necessary for name() , which is why it could be misleading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM