Allow any name in single parameter lambda functions


#1

It would be nice if you could choose a parameter name to your liking for simplified anonymous functions.

Example:

Before:

listOf("Bob","Eva","Zoe").map { it.toUpperCase() }

After:

listOf("Bob","Eva","Zoe").map { name.toUpperCase) }

Advantages:

  • Increases readability
  • One less keyword to remember
  • Free it for other use
  • People coming from other languages might be familiar with it (i.e. Haskell)
  • Consistent with ability to arbitrarily name parameters in explicit lambdas: x -> f(x)

Disadvantages:

  • None… I think

#2

What is “name”? It is undefined.


#3

I’m not sure how allowing to use an arbitrary, undeclared name would be familiar to people coming from any other language, because I haven’t seen this feature anywhere else. In Haskell, the lambda parameter name is explicitly declared, so I’m not sure why this would be familiar to Haskell users.

Also, real code is never a single line. If I encountered such a line in an actual program, I’d have to spend a lot of time trying to understand where “name” comes from - is it a variable from an outer scope? inherited from a base class? imported via an alias? When I see “it”, it’s immediately clear what this means.

Not to mention all the confusion that would arise if you meant to refer to a specific function or variable from an outer scope, made a typo, and Kotlin would interpret it as the lambda parameter according to the “a parameter name to your liking” rule that you propose.


#4

You are right I mixed something up. Haskell’s case of allows to destructure functions and assign arbitrary names:

case box of
    Just content -> print content
    Nothing      -> print "Nothing inside"

For regulary functions you still need to declare them. Maybe I was just confused because I didn’t remember having to find a keyword to refer to the only element in Haskell:

map toUpperCase ["Bob","Eva","Zoe"]

Is there a similar way of achieving that? Java allows method references.


#5

https://kotlinlang.org/docs/reference/reflection.html#function-references


#6

I see it cannot be used for overloaded functions. When the new syntax that allows parameter types is planned?


#7

The documentation here is somewhat misleading and will be updated. No new syntax is planned.


#8

I see… If you plan to update the docs, can you consider adding why it isn’t planned? Thanks!


#9

The updated docs are now live, and I hope it’s clear from them why there isn’t any need for any new syntax.


#10

@yole That’s crystal clear! Thanks