简体   繁体   English

当我使用SortedSet时,为什么“错误:......分歧隐式扩展......”

[英]Why “Error:…diverging implicit expansion…” when I use SortedSet?

I'm working my way through Scala for the Impatient and am struggling to write tests for my solution to Chapter 10's 2nd exercise: Define a class OrderedPoint by mixing scala.math.Ordered[Point] into java.awt.Point. 我正在通过Scala为Impatient工作,我正努力为我的第10章练习的解决方案编写测试:通过将scala.math.Ordered [Point]混合到java.awt.Point中来定义类OrderedPoint。 Use lexicographic ordering, ie (x, y) < (x', y') if x < x' or x = x' and y < y'. 如果x <x'或x = x'且y <y',则使用词典排序,即(x,y)<(x',y')。

My class does what the book asked for, but I can't seem to get it to work with SortedSet. 我的课做了本书要求的内容,但我似乎无法使用SortedSet。

The class definition is like... 类定义就像......

package sfti.ch10

import java.awt.Point

class OrderedPoint(x: Int, y: Int) extends java.awt.Point(x, y) with scala.math.Ordered[Point] {
  override def compare(that: Point): Int = {
    if (getX == that.getX) {
      getY.compare(that.getY)
    } else {
      getX.compare(that.getX)
    }
  }
}

The Spec definition is simple enough, but fails to compile once I put the SortedSet in there. Spec定义很简单,但是一旦我将SortedSet放在那里就无法编译。

package stfi.ch10

import org.scalatest.FlatSpec
import sfti.ch10.OrderedPoint

class Ex02_OrderedPointSpec extends FlatSpec {
  "An OrderedPoint" must "make java.awt.Points comparable" in {
    val p_0_1 = new OrderedPoint(0, 1)
    val p_1_0 = new OrderedPoint(1, 0)
    val p_1_1 = new OrderedPoint(1, 1)
    val p_0_0 = new OrderedPoint(0, 0)

    assert(p_0_0.compare(p_0_0) == 0)
    assert(p_0_0.compare(p_0_1) < 0)
    assert(p_1_1.compare(p_1_0) > 0)

    // this tips over the compiler
    val sortedSet = scala.collection.SortedSet(p_1_1, p_0_0, p_1_0, p_0_1)
  }
}

Error:(19, 53) diverging implicit expansion for type sfti.ch10.OrderedPoint => Comparable[sfti.ch10.OrderedPoint] starting with method $conforms in object Predef val s = scala.collection.SortedSet[OrderedPoint](p_1_1, p_0_0, p_1_0, p_0_1)

Why won't SortedSet respect my Ordered compare? 为什么SortedSet不会尊重我的Ordered比较?

I already looked at What is a diverging implicit expansion error? 我已经看过什么是分歧的隐式扩展错误? and its like they are speaking in tongues. 就像他们说方言一样。 What do I have to do to my OrderedPoint or SortedSet invocation to get the SortedSet to use the compare method from OrderedPoint? 我需要对OrderedPoint或SortedSet调用做什么才能让SortedSet使用OrderedPoint的compare方法?

Change it to 将其更改为

with scala.math.Ordered[OrderedPoint]

Ordered is invariant so the type parameter needs to match exactly. Ordered是不变的,因此type参数需要完全匹配。

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

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