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?
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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With