开发者

How does one "override" an inner class in Scala?

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 cla开发者_开发问答ss? Things like override class Val extends super.Val are not permitted.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜