Passing dependent objects to a parent constructor in Scala

Posted by Nick Johnson on Stack Overflow See other posts from Stack Overflow or by Nick Johnson
Published on 2010-05-15T19:45:38Z Indexed on 2010/05/15 20:44 UTC
Read the original article Hit count: 234

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about scala

Related posts about constructor