by TrianguloY · 3y ago · 0 comments
I'm referring to using
var f = (a) -> code;
Instead of function f(a){ code }
Which are exactly the same.JavaScript (and typescript) prefers them. Is it because of a convention or it really has advantages?
Haskell (and other functional languages) also use them a lot, but I guess in these cases the language is designed around it.
Kotlin, Java and other languages with lambdas doesn't really benefit from them in my opinion. If it's a global variable, a function is just enough and 99% of the times preferred. If it is something local, either inline it or also use a function (Kotlin allows for inlined functions, Java doesn't; and maybe, if you need to capture variables, a local Function variable is the only instance where this is useful, but otherwise please just use a function. * )
Python and other languages with limited or not available lambdas do use functions, and there are rare cases where a lambda would help.
In general, if you are using language X try to use language X's features and best practices. Don't try to program as if you were using language Y, it will only make it more confusing. You can easily see when someone is used to a language and tries to use another without understanding the differences. Going from java to python is a very clear example (classes everywhere! Loops just because!)
* In java, an initialized private Function<> field is 99% of the time useless and worse than just a function. And 99.99% if it is final.
There are some slight differences: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
I believe the reason arrow functions are prefered in his is because of the way `this` is handled: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
(I don't know why they made return mandatory in Kotlin, as a language can function just fine without explicitly writing return everywhere.)
fun sum(a:Int, b:Int) = a+b
In fact, it is even shorter than the lambda equivalent: val sum = {a:Int, b:Int -> a+b }
Even so, if you still need a block body but dislike the mandatory return, you can use a run body (where the last value will automatically be returned). fun sum(a:Int, b:Int) = run {
doThings()
a+b
}
And even in that case you can use let, apply, and all the other syntactic sugar to allow beautiful flows and one-linersYou know, in Groovy, the return is always optional... Kotlin copied the lambda syntax from Groovy but didn't copy that for some reason (notice how this makes the language inconsistent, as "some" blocks require a mandatory return, others don't... Rust for example, like Groovy, does not require return in either situation).
But I remember some of my colleagues were shocked by Groovy not requiring a return :D OMG that makes the code so hard to read!!!!! People just tend to not like anything that goes against what they do in their main language even when that doesn't really make any sense.