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

jayjay93 :

Question summary - How do I convert this to a Scala class?

Issue - Multiple constructors calling different super constructors

Java class -

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

I have been trying to convert these constructors for this class to scala for about a day and I cannot make any headway on how to deal with the following issue - (Multiple constructors calling different base class constructors in Scala). Would anyone mind helping me on a way to approach converting this class? I have read some places said it's not possible to do this with standard super calling in Scala, then how do I accomplish this?

roterl :

The main constructor must be called so any other constructor must call the main or another constructor that will call the main one. The constructor of the super is called in the main constructor as part of the inheritance declaration. This mean you can call only one super constructor.

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)
}
  • note that the BaseClassExample parameters are defined in the main constructor.
  • Instead of use the super class default values, just put them explicitly in the sub class (as the "mode" in the example).
  • since the main constructor must be called you don't need the init method to be called from every constructor (just in the main, or even init in the body directly)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470674&siteId=1
Recommended