简体   繁体   中英

Trait that extends a type argument

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, ie either A or B).

Can I do that, and how?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM