Lawrence Wagerfield
Lawrence Wagerfield

Reputation: 6611

Referencing the subtype within a trait in Scala

With the vast support for generics in Scala, what is the best way to achieve the following cyclic parameter bounds, where C in Command[A, C] is a subtype of itself (i.e. UserCommand or SystemCommand)?

Note: I have omitted the lower/upper type bounds for C - as the question implies, I am unsure how to express this in a way that compiles, or if I'm missing a feature in Scala specifically intended to solve this type of cyclic problem.

trait CommandPrerequisite[-A, +C] {
   val command: C
   def isValid(aggregate: A): Boolean
}

trait Command[A, C] {
   def prerequisites: List[CommandPrerequisite[A, C]]
}

trait SystemCommand extends Command[System, SystemCommand] {
   // System specific definitions.
}

trait UserCommand extends Command[User, UserCommand] {
   // User specific definitions.
}

Upvotes: 0

Views: 122

Answers (1)

Malte Schwerhoff
Malte Schwerhoff

Reputation: 12852

You probably want f-bounded polymorphism. All you need to change is the signature of trait Command:

trait Command[A, C <: Command[A, C]] {

Upvotes: 3

Related Questions