Suppose I have the following class heirarchy:
class A()
class B(a:A)
class C(b:B)
class BaseClass(b:B, c:C)
Now I want to implement a subclass of BaseClass, which is given an instance of A, and constructs instances of B and C, which it passes to its superclass constructor.
If I could use arbitrary expressions, I’d do something like this:
b = new B(a)
c = new C(b)
super(b, c)
Because the second argument to the parent constructor depends on the value of the first argument, though, I can’t see any way to do this, without using a factory function, or a gratuitous hack, such as :
class IntermediateSubclass(b:B) extends BaseClass(b, new C(b))
class RealSubclass(a:A) extends IntermediateSubclass(new B(a))
Is there clean way to do this?
Probably the best way to handle this sort of situation is by writing a factory method in the companion object for the subclass of BaseClass you want to write.
You can make any of those constructor parameters into fields without affecting anything (by prefixing with
val, if you’re not familiar with that syntax):Now new instances of
SBCcan be created with this sort of expression:SBC(aValue)(regardless of whether thevals are used).