The question about Bidirectional Links in Traits with a Single Type, focused on having a reference to this when both the parents and children are the same type.
self is an excellent solution for situations where the parent and children are the same type ... but what if the parent and children are different types as in the code at the end of the question?
The error on the commented line Error rightly complains that:
type mismatch; found :PolyTree.this.type (with underlying type T) required: C
which makes total sense because self is defined as T.
The goal is to be able to write:
val parentOrder = new ParentOrder
val childOrder = new ChildOrder
childOrder.addParent(parentOrder)
where parentOrder is added to childOrder's parents and childOrder is added to parentOrder's children.
Any id开发者_如何学编程ea how to have to structure the code to remove the error and be able to write code like is shown above?
trait PolyTree[T <: PolyTree[T, C], C <: PolyTree[T, C]] { self: T =>
private val _parents: ListBuffer[T] = ListBuffer()
private val _children: ListBuffer[C] = ListBuffer()
def addParent(parent: T): PolyTree[T, C] = {
_parents += parent
parent._children += this // Error
this
}
def addChild(child: C): PolyTree[T, C] = {
_children += child
child._parents += this
this
}
}
Basically the same solution, you need both T and C as self type so :
trait PolyTree[T <: PolyTree[T, C], C <: PolyTree[T, C]] { self: T with C => ...
精彩评论