如何“覆盖”斯卡拉内部课程? [英] How does one "override" an inner class in Scala?
问题描述
在类枚举#Val的Scaladoc中,我可以读取:实现Value类的类,可以覆盖此类来更改枚举的命名和整数识别行为。我很困惑:我如何覆盖一个类?
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.
推荐答案
> Scala(还)没有虚拟类,所以你不能写 override class Val ...
,然后确保调用新的Val
将为新实例动态选择正确的类。而是会根据对封闭类的实例(在这种情况下为枚举
)的引用的类型来选择类。
There are no virtual classes in Scala (yet), so you can't write override class Val ...
, and then be sure that invoking new 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
).
模拟虚拟类的一般技巧是写入 class Val extends super.Val
,然后覆盖一个保护方法一个工厂为类的实例。在这种情况下,您还必须重写方法:
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:
protected def Value(i: Int, name: String): Value = new Val(i, name)
枚举
将仅使用此工厂方法创建 Val
的实例。一般来说,这种模式需要对程序员进行纪律处理,但可以通过将构造函数声明为私有,从而迫使程序员使用工厂方法。
Enumeration
will create instances of Val
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.
这篇关于如何“覆盖”斯卡拉内部课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!