9

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.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • It's possible to define an inner class e.g. in an `object MyEnum extends Enumeration` like so: `class Val(i: Int, name: String) extends super.Val(i, name)`, but it hardly overrides the Enumeration#Val as it doesn't get instantiated at all. – Jean-Philippe Pellet Dec 02 '10 at 17:06

1 Answers1

12

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.

axel22
  • 32,045
  • 9
  • 125
  • 137
  • Thanks for the explanation. Now I'm even more curious about how I'm go about overriding a final method... – Jean-Philippe Pellet Dec 02 '10 at 19:18
  • (Just as an explanation for other readers: the method you mention is actually final in Enumeration.scala.) By the way, you wrote "There are no virtual classes in Scala (yet)". Any evidence this may come in the future? – Jean-Philippe Pellet Dec 02 '10 at 20:27
  • That has been discussed for quite some time now. I think they're planned in the future, but I don't think anybody knows when exactly is this going to happen. http://scala-programming-language.1934581.n4.nabble.com/scala-when-will-Scala-get-virtual-class-support-td2002555.html, http://stackoverflow.com/questions/3035807/what-can-i-do-with-virtual-classes – axel22 Dec 02 '10 at 21:14
  • you can't overrid the Value method, it is final. – Thayne Jun 26 '15 at 22:24