Trait that extends a type argument

这一生的挚爱 提交于 2019-12-11 01:51:56

问题


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



来源:https://stackoverflow.com/questions/36066238/trait-that-extends-a-type-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!