javascalaconstructormultiple-constructors

In Scala, how can I subclass a Java class with multiple constructors?


Suppose I have a Java class with multiple constructors:

class Base {
    Base(int arg1) {...};
    Base(String arg2) {...};
    Base(double arg3) {...};
}

How can I extend it in Scala and still provide access to all three of Base's constructors? In Scala, a subclass can only call one of it's superclass's constructors. How can I work around this rule?

Assume the Java class is legacy code that I can't change.


Solution

  • It's easy to forget that a trait may extend a class. If you use a trait, you can postpone the decision of which constructor to call, like this:

    trait Extended extends Base {
      ...
    }
    
    object Extended {
      def apply(arg1: Int) = new Base(arg1) with Extended
      def apply(arg2: String) = new Base(arg2) with Extended
      def apply(arg3: Double) = new Base(arg3) with Extended
    }
    

    Scala 2 traits may not themselves have constructor parameters, but you can work around that by using abstract members instead.

    (Scala 3 lets traits have constructor parameters.)