我正在尝试为不同但相似的对象类定义自然排序。在 Java 中,我会使用 Comparable
,而在 Scala 中似乎可以使用 Ordered
来做同样的事情。我有以下特点:
trait Positioned extends Ordered[Positioned] {
def position: Int = 1
override def compare(that: Positioned): Int = position - that.position
}
我想将此特性应用于多个案例类,例如:
case class Image(id: String,
override val position: Int = 1) extends Positioned
这很好,但是在运行时,当我在这些 Image
对象的集合上调用 sorted
时,我得到这个错误:
diverging implicit expansion for type scala.math.Ordering[com.myapp.Image]
starting with method $conforms in object Predef
请让我知道这意味着什么以及我可以做些什么来解决它。
最佳答案
你绝对可以做你想做的事:
trait Positioned[T <: Positioned[T]] extends Ordered[T] {
def position: Int = 1
override def compare(that: T): Int = position - that.position
}
case class Image(id: String, override val position: Int = 1) extends Positioned[Image]
scala REPL 内部:
scala> val imgs = Seq(Image("5", 5), Image("4", 4), Image("1", 1), Image("3", 3))
imgs: Seq[Image] = List(Image(5,5), Image(4,4),Image(1,1), Image(3,3))
scala> imgs.sorted
res1: Seq[Image] = List(Image(1,1), Image(3,3), Image(4,4), Image(5,5))
关于scala - Scala 中有序特征的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446260/