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

问题描述 投票:2回答:1

我想让我的案例类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个回答
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]] {
      // ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.