不同类型特征中的双向链接
关于具有单一类型的特征中的双向链接的问题,重点是引用这当父母和孩子都是同一类型时。
对于父级和子级为同一类型的情况,self 是一个很好的解决方案……但是如果父级和子级是不同类型(如问题末尾的代码所示)怎么办?
注释行 Error 中的错误正确地抱怨:
类型不匹配;发现:PolyTree.this.type(具有基础类型 T)必需:C
完全有意义,因为 self 被定义为 T。
目标是能够编写:
val parentOrder = new ParentOrder
val childOrder = new ChildOrder
childOrder.addParent(parentOrder)
这 添加到 childOrder 的父级并且 childOrder 添加到parentOrder 的子级。
知道如何构建代码以消除错误并能够编写如上所示的代码吗?
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
}
}
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 idea 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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上是相同的解决方案,您需要 T 和 C 作为自我类型,因此:
Basically the same solution, you need both T and C as self type so :