一个人如何“超越”? Scala 中的内部类?
在 Enumeration#Val 类的 Scaladoc 中,我可以读到:“实现 Value 类型的类。可以重写该类以更改枚举的命名和整数标识行为。”我很困惑:如何重写一个类?不允许像 override class Val extends super.Val
这样的事情。
In the Scaladoc of class Enumeration#Val, I can read: "A class implementing the Value type. This class can be overridden to change the enumeration's naming and integer identification behaviour." I am puzzled: how do I override a class? Things like override class Val extends super.Val
are not permitted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scala 中还没有虚拟类,因此您无法编写
override class Val ...
,然后确保调用new Val
将动态选择新实例的正确类。相反,会发生的情况是,将根据对封闭类实例的引用类型(在本例中为Enumeration
)来选择该类。模拟虚拟类的一般技巧是编写
class Val extends super.Val
,然后重写用作类实例工厂的受保护方法。在这种情况下,您还必须重写该方法:Enumeration
将仅使用此工厂方法创建Val
的实例。一般来说,这种模式需要程序员遵守纪律,但可以通过将构造函数声明为私有来确保,从而强制程序员使用工厂方法。There are no virtual classes in Scala (yet), so you can't write
override class Val ...
, and then be sure that invokingnew Val
will dynamically choose the right class for the new instance. What would happen instead is that the class would be chosen based on the type of the reference to the instance of the enclosing class (in this case,Enumeration
).The general trick to emulate virtual classes is to write
class Val extends super.Val
, and then override a protected method which serves as a factory for instances of the class. In this case, you would also have to override the method:Enumeration
will create instances ofVal
only using this factory method. In general, this pattern requires discipline on the programmer's part, but can be ensured by declaring the constructors private, forcing the programmer to use the factory method.