Scala overloaded constructors and super

爷,独闯天下 提交于 2020-01-02 05:43:09

问题


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

while it's clear how to develop C class, I can't get how to receive B. Help, please.

P.S. I'm trying to create my own BaseWebPage derived from wicket WebPage which is a common practice for Java


回答1:


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).



来源:https://stackoverflow.com/questions/15623059/scala-overloaded-constructors-and-super

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