17.3. Using @SerialVersionUID and Other Annotations
Problem
You want to specify that a class is serializable, and set the
serialVersionUID
. More generally, you
want to know the syntax for using annotations in your Scala code, and
know which annotations are available.
Solution
Use the Scala @SerialVersionUID
annotation while also having your class extend the Serializable
trait:
@SerialVersionUID
(
1000L
)
class
Foo
extends
Serializable
{
// class code here
}
Note that Scala has a serializable
annotation, but it has been
deprecated since version 2.9.0. The serializable annotation Scaladoc
includes the following note:
instead of @serializable class C, use class C extends Serializable
Discussion
In addition to the @SerialVersionUID
annotation and the Serializable
trait, Scala has other
annotations that should be used for various purposes, including the
cloneable
, remote
, transient
, and volatile
annotations. Based primarily on the
“A Tour of Scala Annotations” web
page, Table 17-3 shows a mapping of
Scala annotations to their Java equivalents.
Table 17-3. Scala annotations and their Java equivalents
Scala | Java |
---|---|
| No equivalent. When added to a class field, it results in getter and setter methods being generated that match the JavaBean specification. |
|
|
|
|
| Per the Scaladoc,
|
| The Java |
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.