从基本抽象类构造子类 [英] Constructing subclasses from base abstract class
本文介绍了从基本抽象类构造子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在抽象类中定义一个构造器,该构造器将创建具体的子类。
I want to define a constructor in an abstract class that will create concrete subclasses.
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
。
What is wrong here? Is this even possible to implement?
Clarification: I want to abstract over the construct method. I do not want to call separately new B
and new C
from either subclasses or companion objects.
推荐答案
如果要创建新实例,则需要显式调用构造函数。
You need to explicitly invoke a constructor if you want create a new instance.
abstract class A {
def newInstance(): this.type;
def construct() : this.type = {
val res = newInstance()
}
}
class B extends A {
def newInstance() = new B()
}
标量擦除在运行时键入Impl,因此无法了解创建类时Impl的含义。
Scala erases type at runtime so there is no way to know what Impl meant when the class was created.
这篇关于从基本抽象类构造子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文