scala self-type:类型参数错误的成员

时间:2011-01-23 15:59:49

标签: scala self-type

这是this question的后续内容。

为什么这段代码无法编译,我该如何解决呢?

trait Vec[V] { self:V =>
  def -(v:V):V
  def dot(v:V):Double

  def norm:Double = math.sqrt(this dot this)
  def dist(v:V):Double = (this - v).norm
}

错误是:

Vec.scala:6: error: value norm is not a member of type parameter V
  def dist(v:V):V = (this - v).norm
                               ^

2 个答案:

答案 0 :(得分:6)

通过将 - 的定义更改为

def -(v:V):Vec[V]

答案 1 :(得分:3)

正确的解决方案是:

trait Vec[V <: Vec[V]] { self:V =>
  def -(v:V):V
  def dot(v:V):Double

  def norm:Double = math.sqrt(this dot this)
  def dist(v:V):Double = (this - v).norm
}

道具Debilski以获得related question的答案。