【发布时间】:2016-11-08 09:49:15
【问题描述】:
我想在将创建具体子类的抽象类中定义一个构造函数。
abstract class A {
type Impl <: A
def construct() : Impl = {
val res = new Impl() //compile error: class type required but A.this.Impl found
// do more initialization with res
}
}
class B extends A {type Impl = B}
class C extends A {type Impl = C}
//...
val b = new B
b.construct() // this should create a new instance of B
这里有什么问题?这甚至可以实施吗?
编辑: 澄清:我想对构造方法进行抽象。我不想从子类或伴随对象中分别调用 new B 和 new C。
【问题讨论】:
-
避免调用 new B 或 new C 有什么好处?
-
我可能有很多子类(B、C、D、...),我想避免重复/样板代码。
-
唯一能做你想做的事就是使用反射。正如我在回答中所说,这不是一个好主意。
-
如果你有很多子类型都在做同样的初始化,你可能有糟糕的设计。一般来说,为什么不直接调用
A的构造函数呢?像这样:class B extends A(param1, ...) { ... }。那么A将是一个适当的抽象,而不仅仅是一些hack。 -
我想要做的是最终在不知道具体类的情况下从类 A 中的方法调用construct()。所以我不能调用 new B()。这就是我试图用 new Impl() 做的事情,但在这里我得到了编译器错误。此错误类似于使用参数化类型(类型擦除)时遇到的错误。所以我认为使用带有清单的反射可能会解决问题 - 根据@Monkey的回答
标签: scala abstract-class abstract-type