2

このコードを機能させるのに問題があります。それを継承するクラスが「子」を持つことを可能にする特性を作成したいのですが、どうやら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
}
4

1 に答える 1

5

thisisPと notを示すには、 self 型を使用する必要があります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
}
于 2015-02-04T22:25:48.353 に答える