扩展类型参数的特征

时间:2016-03-17 16:21:36

标签: scala subclass generic-type-argument

我试过了:

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

并在另一个档案中:

trait C[AB<:AorB] extends AB

但获得error: class type required but AB found

我真正想要做的是说C的子类应该实现AB(而不是AorB,它被用作某种特征-Enum,即A或B)。

我可以这样做,以及如何?

1 个答案:

答案 0 :(得分:4)

我在其中一个相关问题中找到答案&#34;由SO提出(其标题不相关: - ):

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

trait C { this: AorB => }

修改

我用它来获得类型的笛卡尔积之王:

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

所以(在其他文件中),我们可以定义:

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

AorB x CorD

的任意组合等等
相关问题