In Scala, when I call "helloworld".groupBy(_.toLower)
, I get the expected result:
scala> "helloworld".groupBy(_.toLower)
res10: scala.collection.immutable.Map[Char,String] = Map(e -> e, l -> lll, h -> h, r -> r, w -> w, o -> oo, d -> d)
But when I make the groupBy case-sensitive (i.e. "helloworld".groupBy(_)
), I get the following error:
scala> "helloworld".groupBy(_)
<console>:8: error: missing parameter type for expanded function ((x$1) => "helloworld".groupBy(x$1))
"helloworld".groupBy(_)
^
Why doesn't this second example work? Writing "helloworld".groupBy(x => x)
gives the expected result, but this seems unnecessarily verbose.
That's because
"helloworld".groupBy(_)
is actually equivalent to
x => "helloworld".groupBy(x)
So, instead of grouping, by using the former syntax you really define a function. To see this, check the output of
scala> "helloworld".groupBy(_)
<console>:8: error: missing parameter type for expanded function ((x$1) => "helloworld".groupBy(x$1))
"helloworld".groupBy(_)
Aside from that, instead of using x => x
you could always use identity
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With