Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Scala code: (-_._2)

Tags:

scala

Help me understand this Scala code:

sortBy(-_._2)

I understand that the first underscore (_) is a placeholder. I understand that _2 means the second member of a Tuple. But what does a minus (-) stand for in this code?

like image 368
neuromouse Avatar asked Mar 05 '16 13:03

neuromouse


2 Answers

Reverse order (i.e. descending), you sort by minus the second field of the tuple

The underscore is an anonymous parameter, so -_ is basically the same as x => -x

Some examples in plain scala:

scala> List(1,2,3).sortBy(-_)
res0: List[Int] = List(3, 2, 1)

scala> List("a"->1,"b"->2, "c"->3).sortBy(-_._2)
res1: List[(String, Int)] = List((c,3), (b,2), (a,1))

scala> List(1,2,3).sortBy(x => -x)
res2: List[Int] = List(3, 2, 1)
like image 175
Giovanni Caporaletti Avatar answered Oct 21 '22 14:10

Giovanni Caporaletti


Sort by sorts by ascending order as default. To inverse the order a - (Minus) can be prepended, as already explained by @TrustNoOne .

So sortBy(-_._2) sorts by the second value of a Tuple2 but in reverse order.

A longer example:

scala> Map("a"->1,"b"->2, "c"->3).toList.sortBy(-_._2)
res1: List[(String, Int)] = List((c,3), (b,2), (a,1))

is the same as

scala> Map("a"->1,"b"->2, "c"->3).toList sortBy { case (key,value) => - value }
res1: List[(String, Int)] = List((c,3), (b,2), (a,1))
like image 40
Andreas Neumann Avatar answered Oct 21 '22 13:10

Andreas Neumann