A brief implementation of a function that returns its first argument in Scala

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 do 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 is this second example not working? Writing "helloworld".groupBy(x => x)gives the expected result, but it seems overly detailed.

+4
source share
1 answer

It's because

"helloworld".groupBy(_)

virtually equivalent

x => "helloworld".groupBy(x)

So, instead of grouping using the previous syntax, you really define a function. To see this, check the output.

scala> "helloworld".groupBy(_)
<console>:8: error: missing parameter type for expanded function ((x$1) => "helloworld".groupBy(x$1))
              "helloworld".groupBy(_)

In addition, x => xyou can always use instead identity.

+7
source

All Articles