Why using "!" instead of "-" here for "reverse"?

Like @spamegg1 explained, negating a boolean is done with !. For filter, there is also a filterNot, which keeps elements for which the given function returns false.

In sortBy, a - does not mean “reverse”. The sortBy function extracts some key for the objects you want to sort by applying the given function, and then sorts those keys (which means it must be known how to sort them, i.e. there must be an Ordering for their type).

In the code from your other thread, the key you extract is an Int. If you negate two ints, their order is swapped: if a < b, then -a > -b. That is why they are reversed, but this method only works for numbers.

A more clear, albeit a bit more verbose, way which works for any type with an Ordering is to use a reversed Ordering with sorted, e.g.

list.sorted(Ordering.by(_._2).reverse)
//instead of list.sortBy(-_._2)

Ordering.by creates an ordering for the type in your list, the passed in function works like the one you give to sortBy. Note that reverse is called on the Ordering, not on the List`, so it doesn’t first sort in the wrong order and then reverse the whole list.

2 Likes