How to use serialization in Scala (Serializable trait)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.8, “How to use serialization in Scala (Serializable trait).”

Problem

You want to serialize a Scala class and save it as a file, or send it across a network.

Solution

The general approach is the same as Java, but the syntax to make a class serializable is different.

To make a Scala class serializable, extend the Serializable trait and add the @SerialVersionUID annotation to the class:

@SerialVersionUID(100L)
class Stock(var symbol: String, var price: BigDecimal) extends Serializable {
    // code here ...
}

Because Serializable is a trait, you can mix it into a class, even if your class already extends another class:

@SerialVersionUID(114L)
class Employee extends Person with Serializable ...

After marking the class serializable, use the same techniques to write and read the objects as you did in Java, including the Java “deep copy” technique that uses serialization.

Discussion

The following code demonstrates the proper approach. The comments in the code explain the process:

import java.io._

// create a serializable Stock class
@SerialVersionUID(123L)
class Stock(var symbol: String, var price: BigDecimal) extends Serializable {
    override def toString = f"$symbol%s is ${price.toDouble}%.2f"
}

object SerializationDemo extends App {

    // (1) create a Stock instance
    val nflx = new Stock("NFLX", BigDecimal(85.00))

    // (2) write the instance out to a file
    val oos = new ObjectOutputStream(new FileOutputStream("/tmp/nflx"))
    oos.writeObject(nflx)
    oos.close

    // (3) read the object back in
    val ois = new ObjectInputStream(new FileInputStream("/tmp/nflx"))
    val stock = ois.readObject.asInstanceOf[Stock]
    ois.close

    // (4) print the object that was read back in
    println(stock)

}

This code prints the following output when run:

NFLX is 85.00

See Also