循环引用性状的Scala类型错误

循环引用性状的Scala类型错误,scala,types,compiler-errors,cyclic-reference,Scala,Types,Compiler Errors,Cyclic Reference,我很难让这个代码正常工作。我想创建一个特性,允许继承它的类有“子类”,但显然,Child的setParent方法需要一个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) = {

我很难让这个代码正常工作。我想创建一个特性,允许继承它的类有“子类”,但显然,
Child
setParent
方法需要一个
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
}
package net.fluffy8x.thsch.entity
导入scala.collection.mutable.Set

特质父母[P,C

你需要使用自我类型来表明

这是
P
而不是
父母[P,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
}