4

There is something that I can't quite understand hope someone can shed some light.. I have Seq[String]

val strDeps: Seq[String] = ...

and I tried to sort it on the reverse of the using the sortWith method and I get the following error.

scala> print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n"))
<console>:15: error: wrong number of parameters; expected = 2
              print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n"))
                                                                    ^

But when I try sort it without doing a reverse it works fine.

scala> print(strDeps.sortWith(_.compareTo(_) < 0) mkString ("\n"))
// this is fine

Also it works fine without the placeholder syntax

scala> print(strDeps.sortWith((a,b) => a.reverse.compareTo(b.reverse) < 0) mkString ("\n"))
// this works fine too
mericano1
  • 2,914
  • 1
  • 18
  • 25

2 Answers2

11

_ expands only to the smallest possible scope.

The inner _.reverse part is already interpreted as x => x.reverse therefore the parameter is missing inside sortWith.

Debilski
  • 66,976
  • 12
  • 110
  • 133
8
compareTo(_)

Is a partially applied method. It just means "compareTo, but without applying the first parameter". Note that _ is not a parameter. Rather, it indicates the absence of a parameter.

compareTo(_.reverse)

Is a method taking an anonymous function as parameter, the parameter being _.reverse. That translates to x => x.reverse.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681