Scala Pickling and type parameters

六月ゝ 毕业季﹏ 提交于 2019-12-03 03:18:00

Yep, as Andy pointed out:

you need either a scala.pickling.SPickler or a scala.pickling.DPickler (static and dynamic, respectively) in order to pickle a particular type.

Those both already come in the scala.pickling package, so it's enough to just use them in your generic method signature.

You're absolutely correct that you can add an SPickler context-bound to your generic method. The only additional thing which you need (admittedly it's a bit ugly, and we're thinking about removing it) is to add a FastTypeTag context bound as well. (This is necessary for the pickling framework to know what type it's trying to pickle, as it handles primitives differently, for example.)

This is what you'd need to do to provide generic pickling/unpickling methods:

Note that for the unbar method, you need to provide an Unpickler context-bound rather than a SPickler context-bound.

import scala.pickling._
import binary._

object Foo {
  def bar[T: SPickler: FastTypeTag](t: T) = t.pickle
  def unbar[T: Unpickler: FastTypeTag](bytes: Array[Byte]) = bytes.unpickle[T]
}

Testing this in the REPL, you get:

scala> Foo.bar(42)
res0: scala.pickling.binary.BinaryPickle =
BinaryPickle([0,0,0,9,115,99,97,108,97,46,73,110,116,0,0,0,42])

scala> Foo.unbar[Int](res0.value)
res1: Int = 42

Looking at the project, it seems you need either an scala.pickling.SPickler or a scala.pickling.DPickler (static and dynamic, respectively) in order to pickle a particular type.

The pickle methods are macros. I suspect that if you pickle with an SPickler, the macro will require the compile time type of your class to be known.

Thus, you may need to do something similar to:

object Foo {
  def bar(t: SomeClass1) = t.pickle
  def bar(t: SomeClass2) = t.pickle
  def bar(t: SomeClass3) = t.pickle
  // etc
}

Alternatively, a DPickler may do the trick. I suspect that you'll still have to write some custom pickling logic for your specific types.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!