【问题标题】:Are multiple self-types possible?多种自我类型是可能的吗?
【发布时间】:2016-05-23 15:29:09
【问题描述】:

我想执行以下操作,但 self-type 行无法编译。这是我的语法错误还是这不可能?

trait A {
  def aValue = 1
}
trait B {
  def bValue = 1
}
trait C {
  a : A, b : B =>
  def total = a.aValue + b.bValue
}

class T extends C with A with B { ...

【问题讨论】:

    标签: scala


    【解决方案1】:

    你可以有一个单一的自我类型,它是一个复合类型。

    试试这个:

    trait A {
      def aValue = 1
    }
    trait B {
      def bValue = 1
    }
    trait C {
      self: A with B =>
      def total = aValue + bValue
    }
    
    class ABC extends A with B with C
    

    【讨论】:

      【解决方案2】:

      使用一个特征,您可以使用结构类型

      trait C {
        self: { def aValue: Int
                def bValue: Int } =>
      
        def total = aValue + bValue
      }
      
      class ABC extends C {
        def aValue = 1
        def bValue = 1
      }
      

      使用反射。

      但是,首先你不应该因为principle of least power而过度使用自我类型。

      问题中的方法可以通过扩展其他方式简单地添加:

      trait C extends A with B{
        def total = aValue + bValue
      }
      

      或显式输入两种方法:

      trait C {
        def aValue: Int
        def bValue: Int
      
        def total = aValue + bValue
      }
      

      在哪里使用自我类型?

      自类型通常与类一起使用。这是 trait 要求成为所需类的子类的好方法。

      self-type 与 triats 还有一个很好的用途:当您想要使用多重继承来操作类初始化的顺序时。

      【讨论】:

        猜你喜欢
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多