How to perform Serialization and Deserialization in Scala

Serialization and Deserialization in Scala

In this post, We will show you simple program about, How to perform Serialization and Deserialization in Scala programming language. The example program has been tested and shared in the post.

Customer Class (Customer.scala)

package com.dineshkrish.scala

class Customer(custId: Int, custName: String) extends Serializable {
    def getCustId(): Int = {
       return custId;
    def getCustName(): String = {
        return custName;
    override def toString(): String = {
      return "[Customer Id = "+custId+", Customer Name = "+custName+"]";

Serialization and Deserialization (CustomerSerializer.scala)

package com.dineshkrish.scala


class CustomerSerializer {
    def serialize(customer: Customer): File = {
        var file = new File("data.ser");
        var fos = new FileOutputStream(file);
        var oos = new ObjectOutputStream(fos);
        return file;
    def deserialize(file: File): Customer = {
        var fis = new FileInputStream(file);
        var ois = new ObjectInputStream(fis);
        var customer = ois.readObject().asInstanceOf[Customer];
        return customer;

Main Class (Test.scala)

package com.dineshkrish.scala


object Test {

  def main(args: Array[String]): Unit = {

    // creating customer object
    var customer = new Customer(101, "Dinesh Krishnan");

    var cs = new CustomerSerializer();

    // doing serializing
    var file: File = cs.serialize(customer);

    println("Object is serialized...");

    // doing de-serializing
    var obj: Customer = cs.deserialize(file);





Object is serialized...
[Customer Id = 101, Customer Name = Dinesh Krishnan]


1. Scala Programming Language
2. Scala Language Documentation
3. Overriding toString() method

Hello, folks, I am a founder of I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.