Scala overloaded constructors and super

会有一股神秘感。 提交于 2019-12-05 13:32:41

Do you mean something like:

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) {
}

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()
}

All secondary constructor forms must call the primary one. From the language specification (5.3.1 Constructor Definitions):

A class may have additional constructors besides the primary constructor. These are defined by constructor definitions of the form def this(ps1)...(psn) = e. Such a definition introduces an additional constructor for the enclosing class, with parameters as given in the formal parameter lists ps1, ..., psn, and whose evaluation is defined by the constructor expression e. The scope of each formal parameter is the subsequent parameter sections and the constructor expression e. A constructor expression is either a self constructor invocation this(args1)...(argsn) or a block which begins with a self constructor invocation

(emphasis mine).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!