Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Usage of _ in scala lambda functions

Can anyone please explain me why I can do:

a.mapValues(_.size)

instead of

a.mapValues(x => x.size)

but I can't do

a.groupBy(_)

instead of a

a.groupBy(x => x)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...