【问题标题】:Why can't I specify a trait's subclass?为什么我不能指定特征的子类?
【发布时间】:2013-09-28 02:15:50
【问题描述】:
scala> class A
defined class A

scala> trait T extends A { val t = 1 }
defined trait T

//why can I do this?
scala> class B extends T
defined class B

scala> new B
res0: B = B@2e9c76

scala> res0.t
res1: Int = 1

我认为当您编写 trait T extends A 时,它使您只能将 trait T 放在作为 A 子类的类上。那为什么我可以把它放在B上呢?这只适用于你混合的时候吗?为什么在声明类时这是不可能的?

【问题讨论】:

    标签: scala traits


    【解决方案1】:

    "它做到了,所以你只能放 trait T 在作为 A 子类的类上"

    您想要的功能是一个自我类型的注释。另请参阅 Daniel Sobral 对此问题的回答:What is the difference between self-types and trait subclasses? --> 查找依赖注入和蛋糕模式的链接。

    trait A { def t: Int }
    trait B {
      this: A => // requires that a concrete implementation mixes in from A
      def t2: Int = t // ...and therefore we can safely access t from A
    }
    
    // strangely this doesn't work (why??)
    def test(b: B): Int = b.t
    
    // however this does
    def test2(b: B): Int = b.t2
    
    // this doesn't work (as expected)
    class C extends B
    
    // and this conforms to the self-type
    class D extends B with A { def t = 1 }
    

    【讨论】:

      【解决方案2】:

      您只是对特质是什么感到困惑。说class B extends T 仅仅意味着您正在将特征的功能“混合”到 B 的类定义中。因此,在 T 中定义的所有内容或其父类和特征都在 B 中可用。

      【讨论】:

      • 对,但trait T extends A 应该只允许您将特征混合到 A 类。如果您尝试执行 new B with T,它会按预期工作 - 它不会让您这样做。
      • 不,trait T extends A应该只允许您将特征混合到 A 类。它将 A 类的功能添加到特征 T。所以 T 具有 A 类的功能(方法和字段)以及您在 T 中定义的任何内容。当您说 class B extends T 时,您将引入 T A 中的所有内容。
      • @ThomasLockney 你应该看看stackoverflow.com/questions/12854941/… 我想这就是 reguy 所指的
      【解决方案3】:

      你不能做的是:

      scala> class A2
      defined class A2
      
      scala> class B extends A2 with T
      <console>:8: error: illegal inheritance; superclass A2
       is not a subclass of the superclass A
       of the mixin trait T
             class B extends A2 with T
                                     ^
      

      其实写class B extends T和写class B extends A with T是一样的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-03
        • 2019-01-05
        • 2017-02-14
        • 2021-10-05
        相关资源
        最近更新 更多