what is the use case for local lambdas (`val myFun...
# getting-started
y
what is the use case for local lambdas (
val myFun = { foo: Foo -> foo }
), as opposed to local functions (
fun myFun(foo: Foo): Foo = foo
)? unlike some other languages (e.g. Rust), local functions can capture local variables, so the local lambda syntax seems entirely redundant. local functions can also be recursive
k
I think it's just a matter of personal preference. The
fun
style may look nicer to you, but if you want to use it as a method reference you have to prefix it with
::
whereas with a lambda you don't.
Copy code
val myFun: (Foo) -> Foo = { foo: Foo -> foo }
    fun myFun(foo: Foo): Foo = foo  // Note there's no name clash, you can have both named the same!
    listOf(Foo()).map(myFun)        // Refers to the lambda
    listOf(Foo()).map(::myFun)      // Refers to the function
y
I think one of my biggest peeves with
val
-style is that in practice it ends up being more bulky instead of less bulky, because too often input and output types are unable to be inferred and explicit lambda syntax is (imho) "heavier" than function style
also I actually never realized the two don't occupy the same namespace, as you have pointed out
e
there's also anonymous function syntax
Copy code
val myFun = fun(foo: Foo): Foo = foo
👍 1
non-local returns are only possible from
{ }
lambdas and not any
fun
, although that's only usable when inlined (and thus not when captured in a local
val
)
in the end they compile to basically the same thing