本文介绍了如何解决类型的Diverging隐式展开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想始终按键K对我的案例类Event[K, V]进行排序.但是我需要能够比较具有不同值V的事件.我该如何解决这种分散的隐式扩展?

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

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

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

推荐答案

如果您的库方法要求您的类型为Ordering实例,则应提供扩展Ordered的独立实体,从编译器的角度来看这完全没用.观点.请尝试以下操作:

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

这篇关于如何解决类型的Diverging隐式展开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:15