Scala: Ordering contravariance

前端 未结 2 898
迷失自我
迷失自我 2021-02-05 23:23

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

相关标签:
2条回答
  • 2021-02-06 00:07

    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.

    0 讨论(0)
  • 2021-02-06 00:19

    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
    
    0 讨论(0)
提交回复
热议问题