1

作为练习,我应该实现一个特征 PartialOrdered[T]。

trait PartialOrdered[T] {
  def below(that: T): Boolean
  def < (that: T): Boolean = (this below that) && !(that below this)  

  /* followed by other relations <=, >, >=, ==, .. */
}

扩展此特征的类 K 应该在下面实现,使得

a.below(b: K) = { true   if a <= b, 
                  false  in any other case

但是,编译会出现以下错误:

value below is not a member of type parameter T
def < (that: T): Boolean = (this below that) && !(that below this)
                                                        ^

那么我错过了什么?提前致谢

编辑:这是一个示例类 Rectangle(在坐标系中),给出了两个相对的角,如果完全包含一个矩形,则它在另一个下方

case class Rectangle (x1: Int, y1: Int, x2: Int, y2: Int) 
  extends PartialOrdered[Rectangle] {

  def below(r: Rectangle): Boolean = {
    val (rx, ry) = r.topLeft
    val (tx, ty) = this.topLeft
    tx >= rx && ty <= ry &&
    tx + this.width <= rx + r.width &&
    ty - this.height >= ry - r.height
  }

  def width: Int = {...}
  def height: Int = {...}
  def topLeft:(Int, Int) = {...}
}
4

3 回答 3

2

你必须告诉 Scala 这T是一个子类型PartialOrdered[T]

trait PartialOrdered[T <: PartialOrdered[T]] { this: T =>
  def below(that: T): Boolean
  def < (that: T): Boolean = (this below that) && !(that below this)  

  /* followed by other relations <=, >, >=, ==, .. */
}

另请参阅:scala self-type: value is not a member 错误

于 2013-05-04T15:16:32.437 回答
1

这里需要两个概念。一种是F有界多态,另一种是自类型约束。

F 有界多态性,无需深入了解底层类型理论,本质上就是使二元运算符起作用的原因。您基本上定义了一个特征,使其参数成为其自身的子类型:

trait PartialOrdered[T <: PartialOrdered[T]] {
  this: T =>
    def below(that: T): Boolean
    def <(that: T): Boolean =
      (this below that) && !(that below this)
}

为了使不仅this below that工作,而且that below this,我们还需要约束自我类型。这是通过 完成this: T =>的,因此编译器知道它this也是 的一个实例T,而不仅仅是PartialOrdered[T].

然后定义一个类来使用该特征。它需要以自身作为类型参数来扩展 trait:

case class Pair(x: Double, y: Double) extends PartialOrdered[Pair] {
  def below(that: Pair) =
    x <= that.x && y <= that.y
}

object Program extends App {
  println(Pair(1, 2) < Pair(2, 0))
  println(Pair(1, 2) < Pair(1, 3))
  println(Pair(1, 2) < Pair(0, 2))
  println(Pair(1, 2) < Pair(2, 2))
}
于 2013-05-04T15:29:42.453 回答
0

T不一定是的实例,PartialOrdered[T]因此它没有以下方法。我想你的意思是

  def below(that: PartialOrdered[T]): Boolean
  def < (that: PartialOrdered[T]): Boolean = (this below that) && !(that below this)  

?

于 2013-05-04T14:35:18.997 回答