3

I'm trying to use Scala Pickling to program some generic unpickling logic.

Say you have two types, A and B, and you pickle them into a byte array.

You take this byte array and send it to another machine and that's received as a byte array.

Now you need to unpickle it, but you don't know whether the byte array is for type A or type B.

How would you program the unpicking part? Do you make A and B extend another type, say T, and then call unpickle[T], and then pattern match on the result for A or B?

Or do you add a instance variable to T, say a Byte, which uses different number for instances of type A or B, and based on that, call unpickle[A] or unpickle[B]?

UPDATE: Looking into the Scala Pickling testsuite, the closest thing I found is base.scala, which kinda follows the first option.

Galder Zamarreño
  • 5,027
  • 2
  • 26
  • 34
  • Take a look at Heather Miller's [talk](https://speakerdeck.com/heathermiller/instant-pickles-generating-object-oriented-pickler-combinators-for-fast-and-extensible-serialization) on pickle. – David Weber Apr 09 '14 at 05:19

1 Answers1

0

The following works by printing:

It's A
It's B

Code:

import scala.pickling._
import binary._

object MultiTypePickling extends App {

  sealed abstract class Base
  final class A extends Base { override def toString = "A" }
  final class B extends Base { override def toString = "B" }

  val a = new A
  val pa = a.pickle
  val b = new B
  val pb = b.pickle

  // ----
  pa.value.unpickle[Base] match {
    case aa: A =>
      println("It's " + aa)
    case _ =>
      assert(assertion = false)
  }

  pb.value.unpickle[Base] match {
    case bb: B =>
      println("It's " + bb)
    case _ =>
      assert(assertion = false)
  }

}
Galder Zamarreño
  • 5,027
  • 2
  • 26
  • 34