为什么我不能指定特征的子类?
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> 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
I thought that when you write trait T extends A
, it makes it so you can only put trait T
on a class that is a subclass of A
. Why can I put it on B
, then? Is this only for when you mix it in? Why is this not possible when declaring the class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要的功能是自我类型注释。另请参阅 Daniel Sobral 对这个问题的回答:自我类型和特质子类之间有什么区别? --> 查找链接依赖注入和蛋糕模式。
The feature you want is a self-type annotation. See also Daniel Sobral's answer to this question : What is the difference between self-types and trait subclasses? --> look for the links to dependancy-injection and cake-pattern.
你不能做的是:
实际上,编写
class B extends T
与编写class B extends A with T
是一样的。What you can’t do is:
Actually, writing
class B extends T
is the same as writingclass B extends A with T
.你只是对特质是什么感到困惑。说
class B extends T
只是意味着您将特征的功能“混合”到B的类定义中。因此,T或其父类和特征中定义的所有内容都可以在B.You're simply confused about what a trait is. Saying
class B extends T
simply means that you're "mixing in" the functionality of the trait to the class definition of B. So, everything defined in T or it's parent classes and traits, is available in B.您可以指定特征的子类,尽管它是多余的。
考虑到此代码
给出了以下输出,
我们可以推断,由于类 A 的内容被实例化,因为它是隐含的(通过
trait T extends A
),因此这三种形式在语义上是等效的。You can specify the trait's subclass, though it will be redundant.
Considering that this code
gives the following output
we can deduce that since class A's content gets instantiated because it is implied (by
trait T extends A
), the three forms are semantically equivalent.