对于我正在开发的库,我需要提供一种高效、方便且类型安全的序列化 scala 类的方法。理想的情况是用户可以创建一个案例类,并且只要所有成员都是可序列化的,它也应该是无缝的。我在序列化和反序列化阶段都知道类型,因此不需要(也不能)将任何“模式”信息作为序列化格式的一部分(如 Java 对象序列化)。
我一直在玩一些想法,这个想法似乎非常接近。我在这里看到的主要问题是用户必须如何指定类的“应用”和“取消应用”功能。由于这些是真正的静态函数,我想知道是否有可能让编译器找到它。
这是一个自包含的示例:
trait InOut[T] {
// just keeping things simple, for illustration purposes
def toWire(x: T): Array[Byte]
def fromWire(v: Array[Byte] ): T
}
object InOutConversions {
// Pretend these are implemented properly
implicit def Int = new InOut[Int] {
def toWire(x: Int): Array[Byte] = Array[Byte]()
def fromWire(v: Array[Byte] ): Int = 44
}
implicit def String = new InOut[String] {
def toWire(x: String): Array[Byte] = Array[Byte]()
def fromWire(v: Array[Byte] ): String = "blah"
}
// etc... for all the basic types
}
然后我需要一个这样的函数:
def serialize2[T, A1 : InOut, A2 : InOut](unapply : T => Option[Product2[A1, A2]])(obj : T) : Array[Byte] = {
val product : Product2[A1, A2] = unapply(obj).get
implicitly[InOut[A1]].toWire(product._1) ++ implicitly[InOut[A2]].toWire(product._2)
}
这将允许用户非常容易地使用它。例如
case class Jesus(a: Int, b: String)
val j = Jesus(4, "Testing")
serialize2 (Jesus.unapply(_)) (j)
但正如你所看到的,最后一行真的很糟糕。当然必须有可能改进这一点?(给定一个耶稣,我当然可以找到“不适用”的静态方法)