Trait that extends a type argument

2019-07-18 09:13发布

问题:

I tried that:

sealed trait AorB
trait A extends AorB { def apiA:... }
trait B extends AorB { def apiB:... }

and in another file:

trait C[AB<:AorB] extends AB

But get an error: class type required but AB found

What I actually want to do is to say that subclasses of C should implements either A or B (and not AorB which is used as some kind of trait-Enum, i.e. either A or B).

Can I do that, and how?

回答1:

I found the answer in one of the "related questions" proposed by SO (which had an unrelated title :-):

sealed trait AorB
trait A extends AorB { def apiA:... }
trait B extends AorB { def apiB:... }

trait C { this: AorB => }

Edit

I use this to have some king of cartesian product of types:

sealed trait CorD { this: AorB => }
trait C extends CorD { this: AorB => def apiC:... }
trait D extends CorD { this: AorB => def apiD:... }
// the "this: AorB =>" need to be repeated

So (in other files again), we can define:

case class AwithC extends A with C { 
  def apiA:....
  def apiC:....
}

And so on with any combination of AorB x CorD