4 ms·
Still lots of kotlin-features I don't see land in java soon. My favorite is passing a lambda in brackets when it's the last argument to a function. Makes it eas
by matsemann 6y ago
Still lots of kotlin-features I don't see land in java soon.
My favorite is passing a lambda in brackets when it's the last argument to a function. Makes it easy to make semi-dsls and nice-looking code. So instead of
myFun(someVar, { it.something() })
it can be written like
myFun(someVar) {
it.something()
}
or if no parameters to the function other than the lambda like
myFun {
it.something()
}
making the function almost look and behave like a language keyword. I also use extension-functions a lot. Especially for libraries or legacy-java code we wont touch. Where I work we now use Kotlin for all new backend code. And we don't do any Android.
- agumonkey 6y agois that modeled on ruby ?
- vvillena 6y agoThis is a very common idiom in Scala. Function definition is slightly different, but usage is the same.
- agumonkey 6y agoAny example ? or an idiom name I can google ?
- swsieber 6y agoGroovy also does it. I have no idea what the name is though: https://mrhaki.blogspot.com/2009/11/groovy-goodness-passing-closures-to.html?m=1 https://mrhaki.blogspot.com/2009/11/groovy-goodness-passing-...
- jayrhynas 6y agoSwift calls it trailing closure syntax
- agumonkey 6y agoOk so it's an explicit parameter, the function is just ~curried so you can just write it nicely.
- matsemann 6y agoNot sure about the exact name. But kotlin also has "function with receiver" that together with this makes it very easy to write almost a custom domain language on top of kotlin.
- matsemann 6y agoCan't edit, but here's an explanation https://kotlinlang.org/docs/reference/type-safe-builders.html https://kotlinlang.org/docs/reference/type-safe-builders.htm...
- untog 6y agoI don't know, but you can do the exact same thing in Swift.
- pjmlp 6y agoNot at all, it is very common in ML languages, Smalltalk, and even Groovy already had it.
- agumonkey 6y agoI never saw that idiom in any ml classes.. I'm honestly surprised
- pjmlp 6y agoIt is a common idiom for dealing with deterministic resource management, and takes advantage that in ML all functions are single parameter actually. So you can partially specialize, and then the lambda gets the already allocated/opened resource, thus acting as region/arena resource allocator. And you can combine it with currying to apply the concept to multiple kind of parameters.
- deleted 6y ago[deleted]
- thecupisblue 6y agoI abuse the hell out of this and @DSLMarker. Such a small but amazing feature.
- lokedhs 6y agoI do that too, but a real macro facility would be a lot nicer. There are a lot of things that cannot nicely be implemented using the existing syntax.
- thecupisblue 6y agoYep, wish we had that. I had to satisfy myself with annotations and kotlinpoet for now.
- pjmlp 6y agoVery Groovy.