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

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

Leave a Comment