【问题标题】:Trait that extends a type argument扩展类型参数的特征
【发布时间】:2016-07-04 03:17:02
【问题描述】:

我试过了:

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,即A 或B )。

我可以这样做吗?怎么做?

【问题讨论】:

    标签: scala subclass generic-type-argument


    【解决方案1】:

    我在 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 的任意组合以此类推

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 2016-11-28
      • 2022-10-16
      相关资源
      最近更新 更多