How does one “override” an inner class in Scala?

风流意气都作罢 提交于 2020-01-12 14:49:32

问题


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.


回答1:


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).

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)

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.



来源:https://stackoverflow.com/questions/4337601/how-does-one-override-an-inner-class-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!