scala / pickling

Fast, customizable, boilerplate-free pickling support for Scala
lampwww.epfl.ch/~hmiller/pickling
BSD 3-Clause "New" or "Revised" License
831 stars 79 forks source link

generic function with pickling #41

Closed mateuszdraco closed 9 years ago

mateuszdraco commented 10 years ago

Is it possible to write generic function that would pickle given argument of yet unknown type? Something like:

object Barrel {
    def put[A](objx: A) = objx.pickle.value
    def get[A](valx: String) = valx.unpickle[A]
}
mraulim commented 10 years ago

This might help you:

object Barrel {
      def put[A : FastTypeTag : SPickler](objx: A) = objx.pickle.value
      def get[A : FastTypeTag : Unpickler](valx: String) = JSONPickle(valx).unpickle[A]
     }
mateuszdraco commented 10 years ago

Thank you very much for so quick response :)

However, not everything works ;) I did this test:

import scala.pickling._
import json._

case class Info(msg: String)
val m1 = Info("hello")
val s1 = Barrel.put(m1)
val m2 = Barrel.get[Info](s1)

put function works great, it did what I want. But when get is executed error comes up:

scala.reflect.internal.MissingRequirementError: class Info in JavaMirror with sbt.classpath.ClasspathUtilities$$anon$1@4de3b4ee of type class sbt.classpath.ClasspathUtilities$$anon$1
mraulim commented 10 years ago

Did you try your code in REPL? It work great for me:

scala> import scala.pickling._
import scala.pickling._

scala> import json._
import json._

scala> object Barrel {
     | def put[A : FastTypeTag : SPickler](objx: A) = objx.pickle.value
     | def get[A : FastTypeTag : Unpickler](valx: String) = JSONPickle(valx).unpickle[A]
     | }
defined module Barrel

scala> case class Info(msg: String)
defined class Info

scala> Info("hello")
res0: Info = Info(hello)

scala> Barrel.put(res0)
res1: String = 
{
  "tpe": "Info",
  "msg": "hello"
}

scala> Barrel.get[Info](res1)
res2: Info = Info(hello)
mateuszdraco commented 10 years ago

You are right :) I get sbt example and tried it there and it works. It seems I have some other error.

Thanks a lot! :)

mateuszdraco commented 10 years ago

Well, I was a bit too impatient. This works but only in I declare Barrel in REPL. If I try to use come earlier defined object it ends with error I mentioned before.

Also, it seems I have to import plickling and json even if I have this operations encapsulated in Barrel object. I was hoping I could use pickling as a string (json) serializer so it wasn't so important for me to import it everywhere too. But it is minor issue and I can live with it ;)

jsuereth commented 9 years ago

@mateuszdraco FYI - I think you only need to import json._ at the Barrel implementation site. IN any case, We are actively doing this in sbt-serialization, see: https://github.com/sbt/serialization/blob/master/serialization/src/main/scala/sbt/serialization/SerializedValue.scala#L23

Going to close this for now, please re-open if you see issues on master.