11

I want to translate the following piece of code from Java to Scala:

Foo foo = new Foo() { private static final long serialVersionUID = 12345L; }

Class Foo is an abstract class.

How does the equivalent code look like in Scala?

soc
  • 27,983
  • 20
  • 111
  • 215
  • How are the title and the actual question related? – Laurent Pireyn Apr 05 '11 at 11:57
  • Well, I ask in the title how I can add `@SerialVersionUID` to a anonymous class and show an example of a constructed anonymous class with a `serialVersionUID`, which exhibits said question. – soc Apr 05 '11 at 12:35

1 Answers1

10

There is a Scala annotation for adding the ID. But it seems, that you cannot apply this solution to anonymous inner classes. However, according to the Scala FAQ:

In Scala private values that evaluate to a constant known at compile-time are turned into private static final Java variables. This undocumented feature should do the trick for you. Just check out the implementation of lists in Scala (see e.g. src/scala/List.java). Both classes :: and Nil have a field serialVersionUID of the following form: private val serialVersionUID = numeric literal;

The code

object Ser extends Application {
    trait Foo { def xy: Int }
    val x = new Foo with java.io.Serializable { def xy = 2; private val serialVersionUID = 1L }
}

compiles fine with the 2.8.1 compiler. I haven't tested it, though as to whether the serial version of the resulting class is actually the one supplied.

Dirk
  • 30,623
  • 8
  • 82
  • 102
  • Mhh, but this would add it as instance method and not as a class method, right? I don't think that will work ... – soc Apr 07 '11 at 18:58
  • @soc: See the excerpt from the FAQ: "In Scala private values that evaluate to a constant known at compile-time are turned into private static final Java variables." – Dirk Apr 08 '11 at 11:25
  • WTH? I didn't know that and never assumed this would happen ... Thanks a lot! I just wonder if that is all what's needed or if there is some special magic necessary regarding serialVersionUID ... – soc Apr 08 '11 at 12:12
  • @soc: I don't know, but I assume, that it is more general than that: why make an instance variable (or: magic getter or whatsoever) for something known already at compile time to be constant and shared with the same value across all instances of a class? – Dirk Apr 08 '11 at 12:56