如何解决

时间:2017-03-29 18:52:02

标签: scala sorting

我想让我的案例类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))

1 个答案:

答案 0 :(得分:0)

如果您的库方法需要一个Ordering类型的实例,那么您应该提供一个扩展Ordered的indead,这从编译器的角度来看是完全不公平的。请尝试以下方法:

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