Open amnaredo opened 2 years ago
I don't think you really need such a complicated macro to do what you want, Custom Picklers works just fine for this sort of thing. If you want you could probably reduce the boilerplate down to 1 line of code with a helper function.
haoyi-test@ case class TestField(testField: String) extends AnyVal
defined class TestField
haoyi-test@ upickle.default.write(TestField("foo"))
res5: String = """
{"testField":"foo"}
"""
haoyi-test@ upickle.default.write(Seq(TestField("foo")))
res6: String = """
[{"testField":"foo"}]
"""
haoyi-test@ import upickle.Js
import upickle.Js
haoyi-test@ {
case class TestField(testField: String) extends AnyVal
object TestField{
implicit val writer = upickle.default.Writer[TestField]{
case t => Js.Str(t.testField)
}
implicit val reader = upickle.default.Reader[TestField]{
case Js.Str(str) => TestField(str)
}
}
}
defined class TestField
defined object TestField
haoyi-test@ upickle.default.write(Seq(TestField("foo")))
res9: String = """
["foo"]
"""
Sure, that's exactly what your macro does, but it doesn't really need to be a macro... it could be a one line implicit
implicit val readWriter = matthewpflueger.unboxedReadWriter[TestField](TestField.apply, TestField.unapply)
that provides all that that nasty annotation macro adds. Something similar could be dreamed up with for the use case of scala.Enumeration I'm guessing, but haven't looked closely.
To answer your questions...
Original Author: lihaoyi
Hey, thanks for taking the time to write out such a thorough response. I really appreciate the insight!
Original Author: matthewpflueger
I have a large domain made up mostly of value classes as members of large domain objects. For example:
When pickling using the default writer it comes out looking something like:
On a large domain object this looks pretty gross as value classes are pickled as nested objects. To make things a little nicer for consumers of my api, I wanted to unwrap the value class so pickling looks like:
So I took a crack at writing a macro that generates a Writer and Reader for annotated value classes (code at the bottom). I use it like so:
It works well in practice for me. I'm wondering the following:
Anyway, the macro I use for the above (first one I've written so pretty ugly and also domain specific as I don't account for any types I don't use or even try to do it in a general fashion):
Also one for pickling enums (probably could be combined with the one above):
ID: 147 Original Author: matthewpflueger