【问题标题】:How can I solve the Diverging implicit expansion for type如何解决类型的发散隐式扩展
【发布时间】:2019-02-06 18:06:08
【问题描述】:

我想让我的案例类 Event[K, V] 始终按键 K 排序。但我需要能够比较不同值的事件V。如何解决这种发散的隐式展开?

import scala.math.Ordering

object Event {
  case class Event[K, V](key: K, value: V)
    (implicit o: Ordering[K]) extends Ordered[Event[K, _]] {
      override def compare(that: Event[K, _]): Int = o.compare(key, that.key)
    }
}

object Main extends App {
  // mimicking a librarys function 
  def lala[O](e: O)(implicit ordering: Ordering[O]) = ???

  val b = Event.Event("a", 12) <= Event.Event("a", 11.99)    
  lala(Event.Event("a", 12))
}

由于这种发散的隐式扩展,对lala 的调用无法编译:

diverging implicit expansion for type   
scala.math.Ordering[Event.Event[String,Int]] starting with method $conforms 
in object Predef lala(Event.Event("a", 12))

【问题讨论】:

    标签: scala sorting


    【解决方案1】:

    如果您的库方法期望您的类型有一个 Ordering 实例,则您应该提供该类型的扩展 Ordered,从编译器的角度来看,它完全被低估了。请尝试以下方法:

    case class Event[K, V](key: K, value: V)
    
    object Event {
      implicit def eventOrdering[K, V](implicit o: Ordering[K]) =
        new Ordering[Event[K, V]] {
          // ...
        }
    }
    

    【讨论】:

    • 嗯...但是我想将 Event 与不同的值 V 进行比较。一旦我删除了 implicit def eventOrdering[K, _] 中的 V,我最终会遇到相同的编译器错误。
    • 如果您的库需要implicit Ordering[O]O =:= Event[K, V],这是您需要实现的隐式,没有办法解决。
    • 好的,我现在明白了.. 它似乎可以同时使用你的implicit eventOrdering 并且仍然保持案例类为case class Event[K, V](key: K, value: V) (implicit o: Ordering[K]) extends Ordered[Event[K, _]] {...
    猜你喜欢
    • 2017-12-30
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多