There is a feature in Kotlin that I haven't seen in any other programming language and I think is the coolest feature ever.
Extension lambdas: It's a lambda where you specify the value of 'this', where 'this' is the implicit object where to find functions or fields. For example, the function apply() has a lambda as argument where the value of 'this' is the object used to call apply() (Kotlin lambdas are delimited by {})
Oh, so this is pretty cool. Let me try to understand it better. Instead of writing a constructor with ten parameters, you can expose properties that can be set with an extension lambda?
yes, basically, but it has a lot more uses!, for example there is a library that allows you to write html using extension lambdas and it looks like this:
There is a feature in Kotlin that I haven't seen in any other programming language and I think is the coolest feature ever.
Extension lambdas: It's a lambda where you specify the value of 'this', where 'this' is the implicit object where to find functions or fields. For example, the function apply() has a lambda as argument where the value of 'this' is the object used to call apply() (Kotlin lambdas are delimited by
{}
)It creates an instance of StringBuilder and calls the method append() without having to write
this.append()
. In java you have to write this instead:This also works with properties, so you can easily build SDLs:
Oh, so this is pretty cool. Let me try to understand it better. Instead of writing a constructor with ten parameters, you can expose properties that can be set with an extension lambda?
yes, basically, but it has a lot more uses!, for example there is a library that allows you to write html using extension lambdas and it looks like this:
they have the same flexibility as normal lambdas but with a lot less boilerplate
Wow that’s elegant. I imagine you get the added benefit of type checking and whatnot, right?
Yes!