Search code examples
scalaserializationscala-pickling

Scala pickling: how?


I'm trying to use "pickling" serialization is Scala, and I see the same example demonstrating it:

import scala.pickling._
import json._

val pckl = List(1, 2, 3, 4).pickle

Unpickling is just as easy as pickling:

val lst = pckl.unpickle[List[Int]]

This example raises some question. First of all, it skips converting of object to string. Apparently you need to call pckl.value to get json string representation.

Unpickling is even more confusing. Deserialization is an act of turning string (or bytes) into an object. How come this "example" demonstrates deserialization if there is no string/binry representation of object?

So, how do I deserialize simple object with pickling library?


Solution

  • Use the type system and case classes to achieve your goals. You can unpickle to some superior type in your hierarchy (up to and including AnyRef). Here is an example:

    trait Zero
    case class One(a:Int) extends Zero
    case class Two(s:String) extends Zero
    
    object Test extends App {
      import scala.pickling._
      import json._
    
      // String that can be sent down a wire
      val wire: String = Two("abc").pickle.value
    
      // On the other side, just use a case class
      wire.unpickle[Zero] match {
        case One(a) => println(a)
        case Two(s) => println(s)
        case unknown => println(unknown.getClass.getCanonicalName)
      }
    }