Scala重载了构造函数和super [英] Scala overloaded constructors and super
问题描述
我不明白如何在Java上开发类似于以下内容的Scala代码:
I can't understand how to develop Scala code similar to the following on Java:
public abstract class A {
protected A() { ... }
protected A(int a) { ... }
}
public abstract class B {
protected B() { super(); }
protected B(int a) { super(a); }
}
public class C extends B {
public C() { super(3); }
}
虽然很清楚如何开发C类,但我不知道如何以获得B.帮助。
while it's clear how to develop C class, I can't get how to receive B. Help, please.
PS我试图创建自己的派生自wicket WebPage的BaseWebPage,这是Java的一种常见做法
P.S. I'm trying to create my own BaseWebPage derived from wicket WebPage which is a common practice for Java
推荐答案
:
abstract class A protected (val slot: Int) {
protected def this() = this(0)
}
abstract class B protected (value: Int) extends A(value) {
protected def this() = this(0)
}
class C extends B(3) {
}
有, AFAIK,无法从辅助形式之一绕过主要构造函数,即以下操作无效:
There is, AFAIK, no way to bypass the primary constructor from one of the secondary forms, i.e., the following will not work:
abstract class B protected (value: Int) extends A(value) {
protected def this() = super()
}
所有辅助构造函数窗体都必须调用主窗体。来自语言规范(5.3.1构造函数定义):
All secondary constructor forms must call the primary one. From the language specification (5.3.1 Constructor Definitions):
除了主构造函数外,一个类还可以具有其他构造函数。这些
由定义形式def this(ps1)...(psn)= e的构造函数定义。
这样的定义为封闭类引入了一个附加的构造函数,具有
参数,如形式参数列表ps1,...,psn中所给定,其值
由构造函数表达式定义e。每个形式参数的范围是
,后续参数部分和构造函数表达式e。 构造函数
表达式要么是自构造函数调用this(args1)...(argsn),要么是以自构造函数调用开头的块
(重点是我的)。
这篇关于Scala重载了构造函数和super的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!