繁体   English   中英

将Java转换为Scala,如何处理调用超类构造函数?

[英]Converting Java to Scala, how to deal with calling super class constructor?

问题摘要 - 如何将其转换为Scala类?

问题 - 调用不同超级构造函数的多个构造函数

Java类 -

public class ClassConstExample extends BaseClassExample {
    private String xyzProp;
    private string inType = "def";
    private String outType = "def";
    private String flagSpecial = "none";

    public ClassConstExample(final String file, final String header, final String inType, 
             final String outType, final String flag) {
        super(file);
        init(header, inType, outType, flag);
    }

    public ClassConstExample(final String file, final String header, final String inType, 
             final String outType, final String flag, final String mode) {
        super(file, mode);
        init(header, inType, outType, flag);
    }

    public ClassConstExample(final String file, final String header, final String flag){
        super(file);
        //some logic here that's irrelevant to this
        ...
        this.xyxProp = getXYZ(header);
        this.flagSpecial = getFlagSpecial(flag);
    }
    ...
}

我一直在尝试将这个类的构造函数转换为scala大约一天,我无法在如何处理以下问题上取得任何进展 - (多个构造函数在Scala中调用不同的基类构造函数)。 有人会介意帮我改变这门课吗? 我读过一些地方说过用Scala中的标准super调用不可能做到这一点,那么我该如何做到这一点呢?

必须调用主构造函数,以便任何其他构造函数必须调用main或另一个将调用main构造函数的构造函数。 作为继承声明的一部分,在主构造函数中调用super的构造函数。 这意味着你只能调用一个超级构造函数。

class BaseClassExample(file: String, mode: String) {
  def this(file: String) = this(file, "mode")
}

class ClassConstExample(file: String, header: String, inType: String, outType: String, flag: String, mode: String) extends BaseClassExample(file, mode) {
  def this(file: String, header: String, inType: String, outType: String, flag: String) = this(file, header, inType, outType, flag, "mode")
  def this(file: String, header: String, flag: String) = this(file, header, "inType", "outType", flag)
}
  • 请注意,BaseClassExample参数是在主构造函数中定义的。
  • 而不是使用超类默认值,只需将它们显式放在子类中(作为示例中的“模式”)。
  • 因为必须调用主构造函数,所以不需要从每个构造函数调用init方法(只在main中,或者直接在body中调用init)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM