我想要一个通用的矢量抽象类/特征来指定某些方法,例如:
trait Vec
{
def +(v:Vec):Vec
def *(d:Double):Vec
def dot(v:Vec):Double
def norm:Double
}
Run Code Online (Sandbox Code Playgroud)
我想拥有Vec2D并Vec3D扩展Vec:
class Vec2D extends Vec { /* implementation */ }
class Vec3D extends Vec { /* implementation */ }
Run Code Online (Sandbox Code Playgroud)
但是,我怎样才能使它Vec2D只能被添加到其他Vec2D而不是Vec3D?
现在我只是实现Vec2D并且Vec3D没有共同的Vec祖先,但是重复代码变得乏味.我要实现依赖于这些类中的所有我的几何类(如Triangle,Polygon,Mesh,...)两次,一次Vec2D又一次的Vec3D.
我看到了java实现:javax.vecmath.Vector2d并javax.vecmath.Vector3d没有共同的祖先.这是什么原因?有没有办法在scala中克服它?
这是这个问题的后续内容.
我正在尝试使用自我类型在通用超类中实现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 …Run Code Online (Sandbox Code Playgroud)