Usage of _ in scala lambda functions

When you write a.groupBy(_) the compiler understands it as an anonymous function:

x => a.groupBy(x)

According to Scala Specifications ยง6.23, an underscore placeholder in an expression is replaced by a anonymous parameter. So:

  • _ + 1 is expanded to x => x + 1
  • f(_) is expanded to x => f(x)
  • _ is not expanded by itself (the placeholder is not part of any expression).

The expression x => a.groupBy(x) will confuse the compiler because it cannot infer the type of x. If a is some collection of type E elements, then the compiler expects x to be a function of type (E) => K, but type K cannot be inferred…

Leave a Comment