Ordered[Base] を拡張する基本クラスの拡張に問題があります。私の派生クラスは Ordered[Derived] を拡張できないため、TreeMap のキーとして使用できません。TreeMap[Base] を作成し、Derived で比較をオーバーライドするだけで機能しますが、それは私が望むものではありません。派生クラスをキーにできるようにしたいです。これを回避する方法はありますか?
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
}
編集
scala メーリング リストでのこの議論は非常に関連性が高いように思えますが、少し迷ってしまいます。