Understanding Scala Code: (-_._ 2)

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 the tuple. But what does minus ( - ) mean in this code?

+7
scala
source share
2 answers

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

Underscore is an anonymous parameter, so -_ basically matches x => -x

Some examples in regular 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) 
+14
source share

Sort by ascending type by default. To invert the order a - (Minus), you can add, as @TrustNoOne already explained.

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

Longer example:

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

coincides with

 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)) 
+4
source share

All Articles