In Scala, why `_` cannot be used in groupBy here?

I'm trying to calculate the list of occurrences of each character in a word, my current codes are as follows:

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

I think .groupBy((x:Char)=>x) looks awkward and therefore rewrites like this:

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

But then the compiler throws 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 any ideas about this? Or is there a better way to write this?

+6
source share
1 answer

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

Because _ used for many things, it can also mean "plug in the value here." However, the "plug in identity" does not work due to the above value.

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

+11
source

Source: https://habr.com/ru/post/983171/


All Articles