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

SPickler does not support traits #3

Closed mathieuleclaire closed 11 years ago

mathieuleclaire commented 11 years ago

I try to defined a dummy SPickler this way:

class CustomPickler[T](implicit val format: PickleFormat) extends SPickler[T]{
  def pickle(t: T, builder: PBuilder): Unit = {
    println("In my pickle")
    builder.beginEntry(t)
    builder.endEntry
  }
}

then I defined an implicit this way:

  implicit def cPickler = new CustomPickler[X]
  println((new Y(0)).pickle)

where Y extends the trait X:

trait X {
  def id: Int
}

class Y(val id: Int) extends X

but it does not apply the the pickle method I defined in the CustomPickler class, whereas it does if replacing X by Y in the definition of the implicit. Conclusion: SPickler does not support the trait (if I correctly coded the things), which is a big limitation.

markehammons commented 11 years ago

Matthieu, I think this does what you want:

implicit def cPickler[T <: X] = new CustomPickler[T]
heathermiller commented 11 years ago

We don't have much for documentation (yet) of scala-pickling (besides an academic paper which covers some of these things, but is definitely not ideal for developers). Apologies– comprehensive documentation is on the way.

An important detail that you might not know is that SPickler[T] is meant to pickle only objects of type T, but not subtypes of T.

That means that when you define:

    implicit def cPickler = new CustomPickler[X]

A CustomPickler[X] is introduced in the implicit scope, but CustomPicklers for any of X's subtypes are not introduced into implicit scope. So, @markehammons is correct– the easiest way, when supplying your own custom picklers, and dealing with subtypes, is to be explicit that your custom pickler is also suitable for subtypes of X:

    implicit def cPickler[T <: X] = new CustomPickler[T]
heathermiller commented 11 years ago

Could you let us know if this clarifies things/solves your problem?

mathieuleclaire commented 11 years ago

It clarifies this point yes, thanks. I stay tuned for more documentation then !

heathermiller commented 11 years ago

Awesome- thanks, closing this then. :)