Scala Lesson 53 – Serialization | Dataplexa

Serialization in Scala

In this lesson, you will learn about Serialization in Scala. Serialization is the process of converting an object into a format that can be stored or transmitted and later reconstructed.

Serialization is essential for tasks such as saving data to files, sending data over networks, caching, and working with APIs.


What Is Serialization?

Serialization converts an object into a sequence of bytes or a structured format such as JSON or XML.

The reverse process is called Deserialization, where the stored data is converted back into an object.


Why Serialization Is Important

Serialization is widely used in real-world applications for:

  • Saving objects to files or databases
  • Sending objects over a network
  • API communication (JSON/XML)
  • Caching application state
  • Distributed systems

Built-in Serialization in Scala (Java Serializable)

Scala runs on the JVM, so it can use Java’s built-in serialization mechanism.

To make a class serializable, it must extend Serializable.

case class User(name: String, age: Int) extends Serializable

This allows objects of this class to be serialized using Java I/O streams.


Serializing an Object to a File

The following example demonstrates how to serialize an object to a file.

import java.io._

val user = User("Alice", 30)

val out = new ObjectOutputStream(new FileOutputStream("user.ser"))
out.writeObject(user)
out.close()

This writes the object’s state to a file named user.ser.


Deserializing an Object

To reconstruct the object, we deserialize it from the file.

val in = new ObjectInputStream(new FileInputStream("user.ser"))
val restoredUser = in.readObject().asInstanceOf[User]
in.close()

println(restoredUser)

The object is restored with the same data it had when serialized.


Limitations of Java Serialization

While Java serialization works, it has several drawbacks:

  • Performance overhead
  • Large binary output
  • Security risks
  • Poor cross-language support

Because of this, modern Scala applications often prefer structured formats like JSON.


Serialization to JSON (Concept)

JSON is a text-based format that is human-readable and widely supported.

Scala applications commonly serialize objects to JSON for APIs and storage.

case class Product(id: Int, name: String, price: Double)

This object can be converted into JSON using popular libraries.


Manual JSON Representation (Simple Example)

Without external libraries, JSON can be created manually.

val product = Product(1, "Laptop", 999.99)

val json =
  s"""{"id":${product.id},"name":"${product.name}","price":${product.price}}"""

println(json)

This produces a JSON string representation of the object.


Deserializing JSON Manually

Manual deserialization is possible but error-prone.

val jsonString = """{"id":1,"name":"Laptop","price":999.99}"""

// Parsing logic would be required here

In practice, libraries handle this more safely and efficiently.


Common Serialization Libraries in Scala

Popular libraries used for serialization include:

  • Play JSON
  • Circe
  • Jackson
  • uPickle

These libraries provide automatic and type-safe serialization.


Serialization Use Cases in Real Applications

Serialization is heavily used in:

  • REST APIs
  • Microservices communication
  • Distributed systems
  • Big data processing
  • Message queues

Best Practices

  • Prefer JSON or binary formats over Java serialization
  • Keep serialized objects small
  • Handle backward compatibility
  • Avoid serializing sensitive data

📝 Practice Exercises


Exercise 1

Create a serializable case class representing a student.

Exercise 2

Serialize an object of that class to a file.

Exercise 3

Deserialize the object and print its contents.


✅ Practice Answers


Answer 1

case class Student(name: String, grade: Int) extends Serializable

Answer 2 & 3

val student = Student("Bob", 90)

val out = new ObjectOutputStream(new FileOutputStream("student.ser"))
out.writeObject(student)
out.close()

val in = new ObjectInputStream(new FileInputStream("student.ser"))
val restored = in.readObject().asInstanceOf[Student]
in.close()

println(restored)

What’s Next?

In the next lesson, you will learn about Actors Project, where you will build a practical project using concurrency concepts in Scala.