为什么我在以下代码中遇到diverging implicit expansion
编译器异常?
trait Person extends Ordered [Person] {
def age: Int
def compare (that: Person) = this.age.compare(that.age)
}
class Dinner[A <: Person](val people: Seq[A]) {
def who = people.sorted
}
<console>:16: error: diverging implicit expansion for type scala.math.Ordering[A]
starting with method $conforms in object Predef
def who = people.sorted
^
好的,我可以使用people.sorted[Person]
,但是为什么我应该A
是它的子类。
答案 0 :(得分:1)
您指定了如何比较Person
,但是您没有为A <: Person
做比较,并且在people.sorted
中,编译器必须知道如何进行比较。
尝试
trait Person extends Ordered [Person] {
def age: Int
def compare(that: Person): Int = implicitly[Ordering[Person]].compare(this, that)
}
implicit def personOrdering[A <: Person]: Ordering[A] = (x, y) => x.age.compare(y.age)
class Dinner[A <: Person](val people: Seq[A]) {
def who: Seq[A] = people.sorted
}
case class PersonImpl(age: Int) extends Person
val dinner = new Dinner[PersonImpl](Seq(PersonImpl(30), PersonImpl(20)))
dinner.who // List(PersonImpl(20), PersonImpl(30))