Generic "nested members" trait

Viewed 52

I am building a class composed of multiple traits, one of which provides the capability to include a list of "members" of the class:

trait WithNestedMembers[T] {
  val members = new scala.collection.mutable.ListBuffer[T]
}

class MainClass extends WithNestedMembers[MainClass] {
  // ...
}

This seems to work fine.

Now, I would like to use the "nesting" capability in other traits:

trait NestingUser {
  this: WithNestedMembers[NestingUser] =>
  var nestedValue = 0
  def sumNested = nestedValue + members.map(_.nestedValue).sum
}

The definition seems to work fine by itself. However, I cannot use this as part of MainClass. The following gives an error:

class MainClass extends WithNestedMembers[MainClass] with NestingUser {
  // Illegal inheritance, self-type MainClass does not conform to WithNestedMembers[NestingUser]
}

I suspect that I need to use some sort of type bounds somewhere, to explain that WithNestedMembers[MainClass] is good enough for requirement WithNestedMembers[NestingUser]. But where?

1 Answers

Trying making T covariant with +T like so

trait WithNestedMembers[+T] {
  val members = List.empty[T]
}
Related