scala self-type:value不是成员错误

dsg*_*dsg 0 scala self-type

这是这个问题的后续内容.

我正在尝试使用自我类型在通用超类中实现scala中的向量:

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

  def norm:Double = math.sqrt(this dot this)
  def normalize = self / norm
}
Run Code Online (Sandbox Code Playgroud)

这是3D矢量的实现:

class Vec3(val x:Double, val y:Double, val z:Double) extends Vec[Vec3]
{
  def /(d:Double) = new Vec3(x / d, y / d, z / d)
  def dot(v:Vec3) = x * v.x + y * v.y + z * v.z 
  def cross(v:Vec3):Vec3 = 
  {
      val (a, b, c) = (v.x, v.y, v.z)
      new Vec3(c * y - b * z, a * z - c * x, b * x - a * y)
  }

  def perpTo(v:Vec3) = (this.normalize).cross(v.normalize)
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不编译:

Vec3.scala:10: error: value cross is not a member of Vec[Vec3]
  def perpTo(v:Vec3) = (this.normalize).cross(v.normalize)
                                        ^
Run Code Online (Sandbox Code Playgroud)

出了什么问题,我该如何解决?

此外,任何有关自我类型的参考文献都会受到赞赏,因为我认为这些错误是由于我缺乏理解而产生的.

Deb*_*ski 9

要摆脱所有的肮脏,你必须指定type参数V是其子类Vec.现在你可以V随处使用,因为你的特性知道V继承所有Vec[V]方法.

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

  def norm:Double = math.sqrt(this dot this)
  def normalize: V = self / norm
  def dist(v: V) = (self - v).norm
  def nasty(v: V) = (self / norm).norm
}
Run Code Online (Sandbox Code Playgroud)

请注意nasty不能使用Easy Angel方法编译的方法.