2D 和 3D 向量的正确类层次结构 [英] proper class hierarchy for 2D and 3D vectors
问题描述
我想要一个通用的向量抽象类/特征来指定某些方法,例如:
I want to have a general vector abstract class / trait that specifies certain methods, e.g.:
trait Vec
{
def +(v:Vec):Vec
def *(d:Double):Vec
def dot(v:Vec):Double
def norm:Double
}
我想让 Vec2D
和 Vec3D
扩展 Vec
:
I want to have Vec2D
and Vec3D
extend Vec
:
class Vec2D extends Vec { /* implementation */ }
class Vec3D extends Vec { /* implementation */ }
但是,例如,我如何才能使 Vec2D
只能添加到其他 Vec2D
而不能添加到 Vec3D
?
But how can I, for instance, make it so that Vec2D
can only be added to other Vec2D
and not to Vec3D
?
现在我只是在没有共同的 Vec
祖先的情况下实现 Vec2D
和 Vec3D
,但这会因重复代码而变得乏味.我必须实现所有依赖于这些类的几何类(例如 Triangle
、Polygon
、Mesh
、...)两次,一次用于Vec2D
和 Vec3D
.
Right now I'm just implementing Vec2D
and Vec3D
without a common Vec
ancestor, but this is getting tedious with duplicate code. I have to implement all my geometry classes that depend on these classes (e.g. Triangle
, Polygon
, Mesh
, ...) twice, once for Vec2D
and again for Vec3D
.
我看到 java 实现:javax.vecmath.Vector2d
和 javax.vecmath.Vector3d
没有共同的祖先.这是什么原因?有没有办法在 Scala 中克服它?
I see the java implementations: javax.vecmath.Vector2d
and javax.vecmath.Vector3d
do not have a common ancestor. What's the reason for this? Is there a way to overcome it in scala?
推荐答案
As requested,设计基本特征的最有用方法包括 CRTP 和 自类型注释.
As requested, the most useful way of designing the base trait involves both the CRTP and the self-type annotation.
trait Vec[T <: Vec[T]] { this: T =>
def -(v: T): T
def *(d: Double): T
def dot(v: T): Double
def norm: Double = math.sqrt(this dot this)
def dist(v: T) = (this - v).norm
}
如果没有self类型,就不可能调用this.dot(this)
,因为dot
需要一个T
;因此我们需要通过注解来强制执行.
Without the self-type, it is not possible to call this.dot(this)
as dot
expects a T
; therefore we need to enforce it with the annotation.
另一方面,如果没有 CRTP,我们将无法在 (this - v)
上调用 norm
,因为 -
返回一个 T
因此我们需要确保我们的类型 T
有这个方法,例如声明T
是一个 Vec[T]
.
On the other hand, without CRTP, we’ll fail to call norm
on (this - v)
as -
returns a T
and thus we need to make sure that our type T
has this method, e.g. declare that T
is a Vec[T]
.
这篇关于2D 和 3D 向量的正确类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!