In Scala, how can I subclass a Java class with multiple constructors?
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
}
Traits may not themselves have constructor parameters, but you can work around that by using abstract members instead.
EDIT - this is from a question on the scala mailing list which I thought was duplicated here. My answer relates to providing three different constructors (i.e. replicating the Java design), and not extending the class
Assuming that each of your constructors ultimately create the state S
of the object, create a companion object with "static" methods to create this state
object Base {
private def stateFrom(d : Double) : S = error("TODO")
private def stateFrom(s : Str) : S = error("TODO")
private def stateFrom(i : Int) : S = error("TODO")
}
Then create a private constructor taking the state and (public) overloaded constructors which defer to the primary constructor
import Base._
class Base private(s : S) { //private constructor takes the state
def this(d : Double) = this(stateFrom(d))
def this(str : String) = this(stateFrom(str))
def this(i : Int) = this(stateFrom(i))
//etc
}