【问题标题】:Why am I getting a " diverging implicit expansion" error when trying to sort instances of an ordered class?为什么在尝试对有序类的实例进行排序时出现“发散隐式扩展”错误?
【发布时间】: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).maxSeq(Anomalies.CRITICAL, Anomalies.WARN).max[Anomalies.AnomalyType] 正在工作。

谁能帮我理解错误以及为什么指定类型会修复它?有没有办法不必明确指定?

【问题讨论】:

    标签: scala enums implicits


    【解决方案1】:

    指定类型参数即可:

    Seq[Anomalies.AnomalyType](Anomalies.CRITICAL, Anomalies.WARN).max // WARN
    

    Seq(Anomalies.CRITICAL, Anomalies.WARN).max[Anomalies.AnomalyType] // WARN
    

    【讨论】:

    • 你知道为什么吗?
    【解决方案2】:

    为您的序列推断的类型是Seq[Anomalies.AnomalyType with Product with Serializable]。查看this blog post 关于Product with Serializable 的信息以及如何解决它。

    【讨论】:

    • 好帖子!这正是我一直在寻找的那种修复。虽然它并没有完全回答我的问题,他们只是说“在某些情况下它可能会导致推理问题”,没有更多细节,但多亏了你,我开始对正在发生的事情有了很好的理解。非常感谢!
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2020-05-04
    • 2018-07-20
    • 1970-01-01
    • 2020-09-12
    • 2021-03-28
    相关资源
    最近更新 更多