Is there any reason why Scala\'s Ordering
trait is not contravariant? A motivating example follows.
Suppose I want to perform an ordered insert. I may have
A bit more of a detailed answer pulled out of the thread on 'scala-language' linked in the comment above.
The reason that Ordering
is not contravariant is that this doesn't accord sensibly with the notion of specificity used in implicit resolution. Implicit resolution will try to pick the most 'specific' type for a parameter, and considers one type to be more specific than another if it's a subtype of it. This makes sense in covariant cases: I'd rather have an implicit specific to my list of strings than one for any old list. In contravariant cases, however, it wants to pick the wrong thing:
trait Ord[-A]
A <: B
Ord[B] <: Ord[A]
And so it will pick the 'most specific' ordering as being, if available, Ordering[Any]
.
There looks to be a big discussion going on changing the way 'specificity' is defined with regard to contravariant parameters on the scala-language group.
In the current API, these methods prevent it from being contravariant:
/** Return `x` if `x` >= `y`, otherwise `y`. */
def max(x: T, y: T): T = if (gteq(x, y)) x else y
/** Return `x` if `x` <= `y`, otherwise `y`. */
def min(x: T, y: T): T = if (lteq(x, y)) x else y