我想在抽象类中定义一个构造函数来创建具体的子类。构造基类抽象类的子类
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
。
通过避免调用新的B或新的C可以获得什么好处? – Monkey 2011-01-31 06:56:16
我可能有许多子类(B,C,D,...),我想避免重复/样板代码。 – Adrian 2011-01-31 07:27:16
你可以做你想做的唯一方法就是使用反射。正如我在答复中所述,这不是一个好主意。 – Monkey 2011-01-31 07:53:43