在 Scala 中扩展匿名类型的目的是什么?
我试图更好地理解 Scala,但我似乎找不到如下代码的有效用例:
class C extends { def m() { /* ... */ } }
允许此类构造的理由是什么?
谢谢!
I'm trying to get a better understanding of Scala, and I can't seem to find a valid usecase for code like the following:
class C extends { def m() { /* ... */ } }
What is the rationale for allowing such constructs?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想这里唯一的理由是“如果可能的话避免特殊情况”。你可以扩展任何类,匿名类就是一个类,所以你可以扩展匿名类。
I guess the only rationale here is "avoid special cases if possible". You can extend any class, an anonymous class is a class, so you can extend an anonymous class.
事实上,这不是一个匿名类!它是一个早期的初始化程序,并且作为位于其超类之前的构造函数的一部分运行。
引用 另一个 stackoverflow 问题 的出色答案:
如果编写了代码相反
,当 Z 初始化时会发生空指针异常,因为按照正常的初始化顺序(超类在类之前),大小是在名称之前初始化的。
That is not, in fact, an anonymous class! It's an early initializer and it runs as part of the constructor that goes before its superclass.
Quoting the excellent answer from another stackoverflow question:
If the code were written instead as
then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class).
它被称为早期定义和他们处理超类初始化顺序问题。
It's called Early definitions and they deal with super class initialization order problem.