Is there a way mix in the Ordered trait for a covariant generic?
I have the following code:
trait Foo[+T <: Foo[T]] extends Ordered[T] {
def id: Int
override def compare(that : T) : Int = {
this.id compare that.id
}
}
Where I need T covariant and would like ordered to work too. The version above gives the "covariant type in contravariant position error".
You can't use Ordered with a covariant type because it requires the generic type in a contravariant position. Instead, you should use an implicit Orderingdefined in the companion object
trait Foo[+T] {
def id: Int
}
object Foo {
implicit def fooOrdering[A <: Foo[_]]: Ordering[A] = {
new Ordering[A] {
override def compare(x: A, y: A): Int = x.id compare y.id
}
}
}
Any reasonable function that compares object should be take in an Ordering instance for the objects it is comparing, and many do implicitly. For example
case class F(id: Int) extends Foo[Int]
case class G(id: Int) extends Foo[Int]
List(F(1), F(2), F(5), F(3), G(12)).max // = G(12)
Ordered[A] is invariant in A. The old documentation for this trait explains why:
A trait for totally ordered data. Note that since version 2006-07-24 this trait is no longer covariant in a. It is important that the equals method for an instance of Ordered[A] be consistent with the compare method. However, due to limitations inherent in the type erasure semantics, there is no reasonable way to provide a default implementation of equality for instances of Ordered[A]. Therefore, if you need to be able to use equality on an instance of Ordered[A] you must provide it yourself either when inheiriting or instantiating. It is important that the hashCode method for an instance of Ordered[A] be consistent with the compare method. However, it is not possible to provide a sensible default implementation. Therefore, if you need to be able compute the hash of an instance of Ordered[A] you must provide it yourself either when inheiriting or instantiating.
This means if you want to use Ordered[A] you'll explicitly have to provide an implementation of compare for subtypes of Foo.
A workaround can be done with an implicit Ordering[A]:
implicit def ord[A <: Foo[A]] = new math.Ordering[A] {
override def compare(a: A, b: A) = a.id compare b.id
}
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