循环引用特征的 Scala 类型错误

Scala type error for cyclically referenced traits

我无法使此代码正常工作。我想创建一个特征,允许继承它的 class 具有 "children",但显然,ChildsetParent 方法需要 P,但是取而代之的是 Parent[P, C]

package net.fluffy8x.thsch.entity

import scala.collection.mutable.Set

trait Parent[P, C <: Child[C, P]] {
  protected val children: Set[C]
  def register(c: C) = {
    children += c
    c.setParent(this) // this doesn't compile
  }
}

trait Child[C, P <: Parent[P, C]] {
  protected var parent: P
  def setParent(p: P) = parent = p
}

您需要使用自身类型来表明 thisP 而不是 Parent[P, C]。这也需要额外的边界 P <: Parent[P, C]C <: Child[C, P]

trait Parent[P <: Parent[P, C], C <: Child[C, P]] { this: P =>
  protected val children: scala.collection.mutable.Set[C]
  def register(c: C) = {
    children += c
    c.setParent(this)
  }
}

trait Child[C <: Child[C, P], P <: Parent[P, C]] { this: C =>
  protected var parent: P
  def setParent(p: P) = parent = p
}