【发布时间】:2018-08-17 10:24:02
【问题描述】:
关于这个主题有很多问题,但经过一个小时的阅读,我仍然无法理解我做错了什么。这是我拥有的代码的一个最小示例(Scala 2.11):
object Anomalies {
sealed abstract class AnomalyType(val priority: Int)
extends Ordered[AnomalyType] {
override def compare(that: AnomalyType): Int =
this.priority - that.priority
def name = toString()
}
case object CRITICAL extends AnomalyType(0)
case object SERIOUS extends AnomalyType(1)
case object WARN extends AnomalyType(2)
}
当我尝试进行基本比较时,效果很好:
scala> Anomalies.CRITICAL < Anomalies.WARN
res17: Boolean = true
然而,当尝试排序列表时,编译器对我大喊:
scala> Seq(Anomalies.CRITICAL, Anomalies.WARN).max
<console>:26: error: diverging implicit expansion for type
Ordering[Anomalies.AnomalyType with Product with Serializable]
starting with method $conforms in object Predef
Seq(Anomalies.CRITICAL, Anomalies.WARN).max
编辑:
感谢Dmytro Mitin 我现在知道Seq[Anomalies.AnomalyType](Anomalies.CRITICAL, Anomalies.WARN).max 和Seq(Anomalies.CRITICAL, Anomalies.WARN).max[Anomalies.AnomalyType] 正在工作。
谁能帮我理解错误以及为什么指定类型会修复它?有没有办法不必明确指定?
【问题讨论】: