5

I was trying to get into the new Scala Pickling library that was presented at the ScalaDays 2013: Scala Pickling

What I am really missing are some simple examples how the library is used.

I understood that I can pickle some object an unpickle it again like that:

import scala.pickling._

val pckl = List(1, 2, 3, 4).pickle
val lst = pckl.unpickle[List[Int]]

In this example, pckl is of the type Pickle. What exactly is the use of this type and how can I get for example get an Array[Byte] of it?

Björn Jacobs
  • 4,033
  • 4
  • 28
  • 47

1 Answers1

6

If you want wanted to pickle into bytes, then the code will look like this:

import scala.pickling._
import binary._         
val pckl = List(1, 2, 3, 4).pickle
val bytes = pckl.value

If you wanted json, the code would look almost the exact same with a minor change of imports:

import scala.pickling._
import json._         
val pckl = List(1, 2, 3, 4).pickle
val json = pckl.value

How the object is pickled depends on the import type that you chose under scala.pickling (being either binary or json). Import binary and the value property is an Array[Byte]. Import json and it's a json String.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • 2
    Yep, cmbaxter is totally right. The type of the pickled representation is a subtype of `Pickle`. Selecting the `value` from the pickled representation gives you the type you'd expect, `Array[Byte]` for binary, `String` for JSON, etc. – Heather Miller Sep 04 '13 at 11:15
  • Thanks for the answers. Sometimes I get confused when Scala does something implicitly. I'm still used to the more explicit syntax like Java but I'm working on it. ;) – Björn Jacobs Sep 04 '13 at 13:08
  • 1
    Could it be that IntelliJ doesn't understand, which type to use? I imported scala.pickling._ and binary._ and when I call .pickle on an object, IntelliJ tells me it is of the type Pickle, not BinaryPickle. Therefore it tells me that .value is of the type Pickle.this.type#ValueType. The compiler doesn't complain, for it the result type is BinaryPickle. My work-around: calling .pickle.asInstanceOf[BinaryPickle] for now so that it doesn't display an error in the IDE. – Björn Jacobs Sep 04 '13 at 20:01
  • 1
    Very good point, thanks for bringing it up. A few days ago, we introduced a fix which we think should resolve this issue with IntelliJ. In a nutshell, the macros used in the pickling framework now have more precise type signatures that should be picked up by IntelliJ without IntelliJ having to expand the macro. Let us know if you continue to have issues with this! – Heather Miller Sep 11 '13 at 10:28
  • 1
    I wish the documentation on the homepage was provided as an easier to read form rather than a cumbersome PDF meant for the university world. Pickling could be a nice library but I found it very lacking in that point. – user1338062 Dec 23 '13 at 11:26