简体   繁体   English

使用SortedSet发散隐式扩展错误

[英]Diverging implicit expansion error using SortedSet

I'm trying to use a code similar to 我正在尝试使用类似于以下的代码

abstract class A[T] extends Ordered[A[T]] {
  val att:Int

  def compare(that:A[T]) = 
    if (this.att >= that.att)
       1
    else
      -1
}

class B extends A[Int] {
  val att = 1
}

When I try this in Scala 2.11 REPL 当我在Scala 2.11 REPL中尝试此操作时

scala> import scala.collection.immutable.SortedSet
scala> SortedSet[B]()

I get the following error 我收到以下错误

<console>:11: error: diverging implicit expansion for type Ordering[B]
starting with method ordered in trait LowPriorityOrderingImplicits
          SortedSet[B]()

How can I solve this? 我该如何解决?

You need an instance of the Ordering type class to create a SortedList . 您需要Ordering类型类的实例来创建SortedList The ordered method mentioned in the error message will automatically create an Ordering[X] for any type X that's an Ordered[X] . 所述ordered错误消息将自动创建一个提到的方法Ordering[X]的任何类型的X这是一个Ordered[X]

Your B is not an Ordered[B] , however—it only extends Ordered[A[Int]] . 您的B不是Ordered[B] ,但是它仅扩展了Ordered[A[Int]] Ordered is invariant in its type argument, so Ordered[B] and Ordered[A[Int]] have essentially nothing to do with each other. Ordered在其类型参数中是不变的,因此Ordered[B]Ordered[A[Int]]本质上彼此无关。

You can address this issue with F -bounded polymorphism : 您可以使用F界多态性解决此问题:

abstract class A[T, S <: A[T, S]] extends Ordered[S] {
  val att: Int

  def compare(that: S)= 
    if (this.att >= that.att)
      1
    else
      -1
}

class B extends A[Int, B] {
  val att = 1
}

Now B extends Ordered[B] and you can create the sorted set. 现在, B扩展了Ordered[B] ,您可以创建排序后的集合。 Alternatively, you could use your original code and just create a SortedSet[A[Int]] . 另外,您可以使用原始代码并仅创建SortedSet[A[Int]] It's a much better idea to avoid Ordered altogether, though, and just define the Ordering type class instance directly. 不过,最好还是完全避免使用Ordered ,而直接定义Ordering类型类实例。

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

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