Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 class? Things like override class Val extends super.Val are not permitted.

like image 806
Jean-Philippe Pellet Avatar asked Feb 04 '23 00:02

Jean-Philippe Pellet


1 Answers

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.

like image 145
axel22 Avatar answered Feb 12 '23 02:02

axel22