不同类型特征中的双向链接

发布于 2024-11-07 12:46:34 字数 1112 浏览 0 评论 0原文

关于具有单一类型的特征中的双向链接的问题,重点是引用当父母和孩子都是同一类型时。

对于父级和子级为同一类型的情况,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

善良天后 2024-11-14 12:46:34

基本上是相同的解决方案,您需要 T 和 C 作为自我类型,因此:

trait PolyTree[T <: PolyTree[T, C], C <: PolyTree[T, C]]  { self: T with C => ...

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 => ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文