Why does using traits with type member give "error: type mismatch" in subtrait?

scala, traits

Solution

Type `P` defined in `HasParent` is an abstract type. That means each `HasParent` may have another type `P` as long as it satisfies the (upper) type bound.

When you call `setParent` on some `HasParent` with a `T`, you have no guarantee that `this` has the required type of that particular `HasParent`.

Are you sure you did not want to write:

type P = Node with HasChildren

Problem

I want to define some traits that describe different tree nodes as follows: ``` trait Node trait HasParent { this: Node => type P <: Node with HasChildren def parent: P def setParent(parent: P) } trait HasChildren { this: Node => def children: Seq[Node] protected def add[T <: Node with HasParent](child: T) { child.setParent(this) // error: type mismatch; // found : HasChildren with Node // required: child.P // child.setParent(this) } } ``` Can you please explain, why this code doesn't compile? What is wrong?

Original source