I want to make my case class Event[K, V]
be ordered by key K
always. But I need to be able to compare Events of different values 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:
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. 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]] {
// ...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.