循环引用性状的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
}