简体   繁体   English

如何解决类型的Diverging隐式展开

[英]How can I solve the Diverging implicit expansion for type

I want to make my case class Event[K, V] be ordered by key K always. 我想让我的案例类Event[K, V]始终按键K排序。 But I need to be able to compare Events of different values V . 但是我需要能够比较不同值V事件。 How can I solve this diverging implicit expansion? 如何解决这种分散的隐式扩展?

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))
}

The call to lala does not compile because of this diverging implicit expansion: 由于存在这种不同的隐式扩展,因此无法编译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))

If your library method expects an Ordering instance for your type, you should provide that indead of extended Ordered , which is totally underalted from a compiler point of view. 如果您的库方法要求您的类型使用Ordering实例,则应提供扩展Ordered独立实体,从编译器的角度来看,该实体完全被低估了。 Try the following instead: 请尝试以下操作:

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]] {
      // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM