"-" not works for normal sortBy arguments

scala> x
val res18: List[(String, Int)] = List((a,2), (b,1), (c,3))

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

scala> x.sortBy(x=>-(x._2))
       error: value =>- is not a member of List[(String, Int)]
       error: value _2 is not a member of List[(String, Int)]

The first sortBy works. While the second does not work.
Can you help explain it?

Thanks in advance.

It seems that all you need to do is add some white spaces to help the parser.

// This works:
 x.sortBy(x => -(x._2))

// Or even just:
 x.sortBy(x => -x._2)
1 Like

You need a space after => so (x=> -(x._2)) would work, but Scala programmers invariably put space on both sides of => and the parens around x._2 are unnecessary. So the idiomatic way of writing this would be (x => -x._2).


Unrelated to syntax, this may not always do what you expect.

scala> val ps = List("a" -> Int.MinValue, "b" -> 0, "c" -> Int.MaxValue)
val ps: List[(String, Int)] = List((a,-2147483648), (b,0), (c,2147483647))

scala> ps.sortBy(- _._2)
val res0: List[(String, Int)] = List((a,-2147483648), (c,2147483647), (b,0))

More verbose, but safer:

scala> ps.sorted(Ordering.by[(String, Int), Int](_._2)).reverse
val res1: List[(String, Int)] = List((c,2147483647), (b,0), (a,-2147483648))

…or (pairs are ordered by right element by default):
[EDIT: Nonsense, sorry, default ordering for pairs is by first/left element, then by right.]

scala> ps.sorted(implicitly[Ordering[(String, Int)]].reverse)
val res2: List[(String, Int)] = List((c,2147483647), (b,0), (a,-2147483648))
1 Like