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).”


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


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:

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:

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.


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


// create a serializable Stock class
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"))

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

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


This code prints the following output when run:

NFLX is 85.00

See Also