Trait that extends a type argument
Asked Answered
M

1

2

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?

Madalene answered 17/3, 2016 at 16:21 Comment(0)
M
4

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

Madalene answered 17/3, 2016 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.