对于我正在开发的库,我需要提供一种高效、方便且类型安全的序列化scala类的方法。理想情况是,如果用户可以创建case类,并且只要所有成员都是可序列化的,那么它也应该是可序列化的。在序列化和反序列化阶段,我都精确地知道类型,因此不需要(也负担不起)将任何"模式"信息作为序列化格式的一部分(如Java对象序列化)。
我一直在考虑一些想法,这个似乎很接近。我在这里看到的主要问题是,用户必须如何指定类的"应用"one_answers"取消应用"函数。因为这些都是真正的静态函数,我想知道是否有可能让编译器找到它。
下面是一个独立的例子:
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)
但是正如你所看到的,最后一行真的很恶心。那肯定有可能改进吧?(给定一个耶稣,我当然可以找到'unapply'静态方法)
由于没有获得给定case类的伴侣对象的通用方法,因此需要添加一些额外的工作。我看到三个选项:
- 你可以使用结构类型,但是你会失去性能
- 你可以使用一个小的类型类来隐式解析正确的
unapply
方法。 - 可以为case类实例添加
toTuple
方法。
trait ToTuple2[A1,A2] {
def toTuple: (A1,A2)
}
case class Jesus(a: Int, b: String) extends ToTuple2[Int,String] {
val toTuple = (a,b)
}
def serialize2[T <: ToTuple2[A1,A2], A1 : InOut, A2 : InOut](obj : T): Array[Byte] = {
val product : Product2[A1, A2] = obj.toTuple
implicitly[InOut[A1]].toWire(product._1) ++ implicitly[InOut[A2]].toWire(product._2)
}
选项2的代码示例:
case class Jesus(a: Int, b: String)
trait Unapply2[T,A1,A2] {
def asTuple( t: T ): (A1,A2)
}
implicit val UnapJesus = new Unapply2[Jesus,Int,String] {
def asTuple( j: Jesus ) = Jesus.unapply(j).get
}
def serialize2[T, A1, A2](obj : T)
(implicit unap: Unapply2[T,A1,A2], inout1: InOut[A1], inout2: InOut[A2]) : Array[Byte] = {
val product : Product2[A1, A2] = unap.asTuple(obj)
inout1.toWire(product._1) ++ inout2.toWire(product._2)
}
你应该看看SBinary,它看起来很像