I'm having trouble extending a base class that extends Ordered[Base]. My derived class can't extend Ordered[Derived] so can't be used as a key in a TreeMap. If I create a TreeMap[Base] and then just override compare in Derived that works but it's not what I want. I would like to be able to have the derived class as a key. Is there a way around this?
case class A(x: Int) extends Ordered[A] {
def compare(that: A) = x.compare(that.x)
}
// Won't compile
// case class B(val y : Int) extends A(1) with Ordered[B] {
// def compare(that: B) = x.compare(that.x) match {
// case 0 => y.compare(that.y)
// case res => res
// }
// }
// Compiles but can't be used to define a TreeMap key
case class B(y: Int) extends A(1) {
override def compare(that: A) = that match {
case b: B => x.compare(b.x) match {
case 0 => y.compare(b.y)
case res => res
}
case _: A => super.compare(that)
}
}
def main(args: Array[String]) {
TreeMap[B, Int]() // Won't compile
}
Edit
This discussion on the scala mailing list seems to be very relevant but it loses me a bit.