2

我无法让这段代码正常工作。我想制作一个特征,允许继承它的类有“孩子”,但显然,Child'ssetParent方法想要 a P,但得到 a 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
}
4

1 回答 1

5

You need to use self types to indicate that this is P and not Parent[P, C]. This will also require extra bounds P <: Parent[P, C] and 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
}
于 2015-02-04T22:25:48.353 回答