Reputation: 4961
I want to invoke the constructor of the sub-class from the super-class (Tree[A]
) to create additional instances of the sub-class of type A
(Part
or Project
). It seems there must be a way that is better than the mess of creating the intermediate method newChild
since things like List
work. I have heard the maybe CanBuildFrom may address this problem.
Extract from working code:
abstract class Tree[A](parent: Option[A], key: Int) {
protected def newChild(aKey: Int): A
lazy val children: List[A] = childrenOf.map(newChild(_))
...
}
case class Part(parent: Option[Part], key: Int) extends Tree[Part](parent, key) {
protected def newChild(aKey: Int) = Part(Some(this), aKey)
...
}
case class Project(parent: Option[Project], key: Int) extends Tree[Project](parent, key) {
protected def newChild(aKey: Int) = Project(Some(this), aKey)
...
}
...
"*" #> <ul>{Part(None, pKey).expandAsHtml}</ul>
What is a better way to use a Scala sub-class constructor for a member within the super-class?
Upvotes: 0
Views: 809
Reputation: 101
To my knowledge, the only way to achieve this is by using reflection.
I found a tutorial here: http://www.heimetli.ch/java/create-new-instance.html
This way you can get the constructor of the subclass within your superclass and call it to create a new instance of your subclass.
However you somehow would have to make sure that your subclasses implement constructors with a specific argument list.
Upvotes: 0
Reputation: 61369
You're looking at it backwards. When an object is created, its constructor is called; this delegates to its superclass's constructor either by default or by explicit invocation. You can't call the subclass's constructor from the superclass's constructor, because it's the subclass's constructor that called the superclass's constructor in the first place.
You need to look at your logic and remember that the way a subclass is known is that it is being directly instantiated; it's not that the superclass is being instantiated with the subclass as some kind of parameter, instead the superclass is instantiated as a step in instantiating the subclass, and the superclass should only know about its own structure, leaving subclass details to the subclass constructor that triggered the superclass.
Upvotes: 1