我无法扩展扩展 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 邮件列表上的这个讨论似乎非常相关,但它让我有点失落。