定义方法以返回扩展它的类的类型 [英] define method to return type of class extending it
问题描述
我希望能够做这样的事情:
I'd like to be able to do something like this:
trait A {
def f(): ???_THE_EXTENDING CLASS
}
class C extends A {
def f() = self
}
class D extends A {
def f() = new D
}
class Z extends D {
def f() = new Z
}
鉴于上面的代码,以下将无法编译
And the following would not compile, given the above code
class Bad1 extends A {
def f() = "unrelated string"
}
class Bad2 extends A {
def f() = new C // this means that you can't just define a type parameter on
// A like A[T <: A] with f() defined as f: T
}
class Bad3 extends D // f() now doesn't return the correct type
这种关系有名字吗?它是如何在 Scala 中注释/实现的?
Is there a name for this kind of relationship? And how is it annotated/implemented in Scala?
如您所见,以下类型的作品:
The following sort of works, as you can see:
scala> trait A {
| def f: this.type
| }
defined trait A
scala> class C extends A {
| def f = this
| }
defined class C
scala> class D extends A {
| def f = new D
| }
<console>:7: error: type mismatch;
found : D
required: D.this.type
def f = new D
^
有没有办法解决这个问题?
Is there a way to get around that?
使用第二个系统,我可以做到这一点,这符合D类的定义:
Using the second system, I can do this, which is good up to the definition of class D:
scala> trait A[T <: A[T]] { def f(): T }
defined trait A
// OR
scala> trait A[T <: A[T]] { self: T =>
| def f(): T
| }
scala> class C extends A[C] { def f() = new C }
defined class C
scala> class D extends C
defined class D
scala> (new D).f
res0: C = C@465fadce
推荐答案
恐怕没有可能从扩展类知道什么是扩展类.
I'm afraid there is no possibility to know what is the extended class from the extending class.
最接近您想要的东西是类似于 C++ 中众所周知的 Curiously Recurring Template Pattern (CRTP).
The closest to what you'd like to have is something similar to Curiously Recurring Template Pattern (CRTP) well known from C++.
trait A[T <: A[T]] {
def f(): T;
}
class C extends A[C] {
def f() = new C
}
class D extends A[D] {
def f() = new D
}
这篇关于定义方法以返回扩展它的类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!