Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise implementation of a function that returns its first argument in Scala

Tags:

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.

like image 430
Mansoor Siddiqui Avatar asked Mar 21 '23 21:03

Mansoor Siddiqui


1 Answers

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.

like image 178
fotNelton Avatar answered Apr 24 '23 02:04

fotNelton