Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

scala self-type: value is not a member error

This is a followup to this question.

I'm trying to implement vectors in scala with a generic super class using self-types:

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
}

Here's an implementation of a 3D vector:

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)
}

Unfortunately this doesn't compile:

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

What's going wrong, and how do I fix it?

Additionally, any references on self-types would be appreciated because I think these errors are cropping up from my lack of understanding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get rid of all the nastiness, you have to specify that the type parameter V is a subclass of Vec. Now you can just use V everywhere, because your trait knows that V inherits all Vec[V] methods.

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
}

Note the method nasty which won’t compile with Easy Angel’s approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...