我正在看一些具有以下形式的Java类:
public
abstract
class A <E extends A<E>> implements Comparable <E> {
public final int compareTo( E other ) {
// etc
}
}
public
class B extends A <B> {
// etc
}
public
class C extends A <C> {
// etc
}
我在这里使用"可比较"只是为了说明通用参数"E"的可能用法.泛型/继承的这种用法是否有名称?它是干什么用的?
我的印象是,这允许抽象类提供方法的通用实现(例如compareTo),而不必在子类中提供它.但是,在此示例中,与继承方法不同,它会限制子类在同一子类的其他实例上调用compareTo,而不是任何"A"子类.这听起来不错吗?
无论如何,只是好奇,如果有任何大师之前已经看到过这一点,并知道它做了什么.
谢谢!
我知道在Scala中不推荐使用case类继承,但为了简单起见,我在下面的例子中使用了它:
scala> case class Foo(val f: String) { def foo(g: String): Foo = { this.copy(f=g) }}
defined class Foo
scala> case class Bar(override val f: String) extends Foo(f)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
defined class Bar
scala> Bar("F")
res0: Bar = Foo(F)
scala> res0.foo("G")
res1: Foo = Foo(G)
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.但是,我真正想要的是能够foo()在Foo中编写一个方法,当在类型为Bar的对象上调用时返回Bar类型的对象,而不必重新实现类Bar中的方法.有没有办法在Scala中执行此操作?
这是这个问题的后续内容.
为什么这段代码无法编译,我该如何解决?
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
}
Run Code Online (Sandbox Code Playgroud)
错误是:
Vec.scala:6: error: value norm is not a member of type parameter V
def dist(v:V):V = (this - v).norm
^
Run Code Online (Sandbox Code Playgroud) 这是这个问题的后续内容.
我正在尝试使用自我类型在通用超类中实现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)