How to use @SerialVersionUID and other Scala annotations

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 17.3, “How to use @SerialVersionUID and other Scala annotations.”

Problem

You want to specify that a Scala 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
scala.beans.BeanProperty No equivalent. When added to a class field, it results in getter and setter methods being generated that match the JavaBean specification.
scala.cloneable java.lang.Cloneable
scala.deprecated java.lang.Deprecated
scala.inline Per the Scaladoc, @inline “requests that the compiler should try especially hard to inline the annotated method.”
scala.native The Java native keyword
scala.remote java.rmi.Remote
scala.serializable java.io.Serializable
scala.SerialVersionUID serialVersionUID field
scala.throws throws keyword
scala.transient transient keyword
scala.unchecked No equivalent. According to its Scaladoc, it designates that “the annotated entity should not be considered for additional compiler checks.”
scala.annotation.varargs Used on a field in a method, it instructs the compiler to generate a Java varargs-style parameter
scala.volatile volatile keyword

As one example of these annotations, the current nightly version of the Scala Remote Scaladoc states that the following Scala code and Java code are equivalent:

// scala
@remote trait Hello {
    def sayHello(): String
}

// java
public interface Hello extends java.rmi.Remote {
    String sayHello() throws java.rmi.RemoteException;
}

Recipe 17.6, “When Java Code Requires JavaBeans” provides examples of the BeanProperty annotation.

See Also