【问题标题】:Efficiently serializing case classes有效地序列化案例类
【发布时间】:2011-12-06 15:38:39
【问题描述】:

对于我正在开发的库,我需要提供一种高效、方便且类型安全的方法来序列化 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)

但是正如你所看到的,最后一行真的很糟糕。当然必须有可能改进这一点? (给定一个耶稣,我肯定能找到“不适用”的静态方法)

【问题讨论】:

    标签: scala serialization case-class


    【解决方案1】:

    因为没有获取给定案例类的伴随对象的通用方法,您将添加一些额外的工作。我看到三个选项:

    1. 您可以使用结构类型,但会降低性能
    2. 您可以使用小型类型类来隐式解析正确的unapply 方法。
    3. 您可以将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,看起来很相似。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 2019-03-06
    • 2011-05-03
    • 2016-07-02
    • 1970-01-01
    • 2013-08-12
    • 2011-06-29
    • 1970-01-01
    相关资源
    最近更新 更多