You can call an auxiliary constructor in the base class via the derived class primary constructor:
class Base(n:Int) {
def this(n:Int, i:Int) = {
this(n)
println(i)
}
}
class Derived(n:Int, i:Int) extends Base(n, i)
Is there a syntax for calling an auxiliary base-class constructor from an auxiliary derived-class constructor? This doesn't work:
class Derived2(n:Int) extends Base(n) {
def this(n:Int, i:Int) = {
super.this(n, i) // Can't do this
println(i)
}
}
In other languages, you can do this, but you must call the base-class constructor first, which is why I tried to do it here.
Note that I am looking for the syntax for the call rather than alternative ways to achieve the same result.
In Scala you have to go through the default constructor no matter what, which forces you to choose one super construction in your class instantiation. This is basically what you're trying to do in terms of java:
Since in Scala you have to go through the default constructor this is what's happening:
So, as is normal in Java, you can only call
super
orthis
as the first line of your constructor implementation. Since Scala forces the call to the default constructor, there's no way around only using one implementation of theBase
constructor.There is no work around, as this isn't really dogmatic Scala. I would suggest changing your design here. Inheritance in Scala is usually done through traits, not classes or abstract classes.
Here's what an alternative might look like using a trait: