bb94
bb94

Reputation: 1304

Scala type error for cyclically referenced traits

I'm having trouble getting this code to work. I want to make a trait that allows a class that inherits it to have "children", but apparently, Child's setParent method wants a P, but gets a Parent[P, C] instead.

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
}

Upvotes: 2

Views: 59

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

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
}

Upvotes: 5

Related Questions