DEV Community

Discussion on: The Coolest Programming Language Features

Collapse
 
cout970 profile image
cout970

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

StringBuilder().apply {
  append("hello")
  append(" ")
  append("world")
  append("!")
}

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:

StringBuilder s = new StringBuilder();
s.append("hello")
s.append(" ")
s.append("world")
s.append("!")
s

This also works with properties, so you can easily build SDLs:

message {
  author = "Cout970"
  subject = "Hello"
  content = "Hello world!"
  method = Method.POST
  send(to = "everybody")
}
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

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?

Collapse
 
cout970 profile image
cout970 • Edited

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:

html {
  head {
    title { +"Page title" }
  }
  body {
    h1{ + "Cool article" }
    p { +"article content" }
  }
}

they have the same flexibility as normal lambdas but with a lot less boilerplate

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Wow that’s elegant. I imagine you get the added benefit of type checking and whatnot, right?

Thread Thread
 
cout970 profile image
cout970

Yes!