您可以通过派生类的主构造函数在基类中调用辅助构造函数:
class Base(n:Int) {
def this(n:Int, i:Int) = {
this(n)
println(i)
}
}
class Derived(n:Int, i:Int) extends Base(n, i)
是否有用于从辅助派生类构造函数调用辅助基类构造函数的语法?这不起作用:
class Derived2(n:Int) extends Base(n) {
def this(n:Int, i:Int) = {
super.this(n, i) // Can't do this
println(i)
}
}
在其他语言中,您可以执行此操作,但是必须首先调用基类构造函数,这就是我在此处尝试执行此操作的原因。
请注意,我在寻找该调用的语法,而不是获得相同结果的替代方法。
在Scala中,无论如何,您都必须通过默认构造函数,这将迫使您在类实例化中选择一个超级构造。基本上,这就是您要使用Java进行的操作:
public class Derived2 extends Base {
public Derived2(int n, int i) {
super(n, i);
}
public Derived2(int n) {
super(n);
}
}
由于在Scala中,您必须通过默认的构造函数,因此发生了这种情况:
public class Derived2 extends Base {
public Derived2(int n, int i) {
this(n);
super(n, i); //does not compile
}
public Derived2(int n) {
super(n);
}
}
因此,与Java中的正常情况一样,您只能调用super
或this
作为构造函数实现的第一行。由于Scala会强制调用默认构造函数,因此无法仅使用Base
构造函数的一种实现。
没有解决方法,因为这不是真正的教条式的Scala。我建议在这里更改您的设计。Scala中的继承通常是通过特征而不是类或抽象类完成的。
这是使用特征的替代品的外观:
trait Base2 {
val a:Int
}
class Derived3(n: Int) extends Base2 {
val a = n
def this(n: Int, i: Int) = {
this(n)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句