Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21693

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

Upvotes: 4

Views: 211

Answers (1)

fotNelton
fotNelton

Reputation: 3894

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.

Upvotes: 7

Related Questions