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

import java.io.File
import java.io.FileOutputStream
import java.io.ObjectOutputStream
import java.io.FileInputStream
import java.io.ObjectInputStream

class CustomerSerializer {
  
    def serialize(customer: Customer): File = {
      
        var file = new File("data.ser");
        
        var fos = new FileOutputStream(file);
        
        var oos = new ObjectOutputStream(fos);
      
        oos.writeObject(customer);
        
        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

import java.io.File

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);

    println(obj)

  }

}

Output

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

References

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

Hello everyone, I am a Founder of dineshkrish.com.