Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, why `_` can't be used in groupBy here?

I am trying to calculate the occurrence list of each character in a word, my current codes looks like this:

"hello"
  .groupBy((x:Char)=>x)
  .map(a=>(a._1, a._2.length))

I think the .groupBy((x:Char)=>x) looks clumsy and therefore rewrite like this:

"hello"
  .groupBy(_)
  .map(a=>(a._1, a._2.length))

But then the compiler throw an error

Error:(1, 18) missing parameter type for expanded function ((x$1) => "hello".groupBy(x$1).map(((a) => scala.Tuple2(a._1, a._2.length))))
"hello".groupBy(_).map(a=>(a._1, a._2.length))

            ^

Does anyone have ideas about this? Or is there better way to write this?

like image 896
Hanfei Sun Avatar asked Mar 01 '15 06:03

Hanfei Sun


1 Answers

x.groupBy(_), like any method x.foo(_), means "turn this method into a function", i.e. y => x.groupBy(y).

Because _ is used for many things, it also can mean "plug in the value here". However, the "plug in identity" doesn't work because of the meaning above.

You can do x => x or identity to get what you intend by _.

like image 135
Rex Kerr Avatar answered Sep 20 '22 22:09

Rex Kerr