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?
File -> Settings -> Editor -> Inspections -> Java -> Serialization issues : Find serialization class without serialVersionUID and check it. Back to the editor, clicks on the class name, ALT + ENTER (Windows), it will prompts the Add serialVersionUID field option. A new serialVersionUID is auto-generated.
SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.
If serialVersionUID is not provided in a Serializable class, the JVM will generate one automatically. However, it is good practice to provide the serialVersionUID value and update it after changes to the class so that we can have control over the serialization/deserialization process.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With