为什么Scala可以序列化Function而不是PartialFunction?

时间:2016-06-14 00:49:26

标签: java scala serialization closures

我有2个函数(其中1个是部分的)在对象下类似地定义:

  val partialFn: scala.PartialFunction[String, Int] =
    new AbstractPartialFunction[String, Int] {

      override def isDefinedAt(v: String): Boolean = {
        counter += 1
        if (v == "abc") true
        else false
      }

      override def applyOrElse[A1 <: String, B1 >: Int](v: A1, default: A1 => B1): B1 = {
        counter += 1
        if (v == "abc") {
          v.length
        }
        else {
          default(v)
        }
      }
    }

  val optionFn: (String) => Option[Int] = {
    (v: String) => {
      counter += 1
      if (v == "abc") {
        Some(v.length)
      }
      else {
        None
      }
    }
  }

当它们都包含在Option(绝对可序列化)中并被序列化/反序列化时,其中一个失败了:

java.io.NotSerializableException: ***.extractors.ExtractorSuite$$anon$1
Serialization stack:
    - object not serializable (class: ***.extractors.ExtractorSuite$$anon$1, value: <function1>)
    - field (class: scala.Some, name: x, type: class java.lang.Object)
    - object (class scala.Some, Some(<function1>))
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:47)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:101)
    at ***.tests.TestMixin$$anonfun$assertSerializable$1.apply(TestMixin.scala:61)

...

知道为什么PartialFunction和amp;之间存在如此大的差异共同的功能?

1 个答案:

答案 0 :(得分:2)

因为您明确创建AbstractPartialFunction而未展开Serializable。如果对new AbstractFunction1[String, Int] { ... }执行相同操作,则它也不可序列化。另一方面,当您使用匿名函数语法时,编译器会生成一个扩展Serializable的类。这包括匿名部分函数语法:

scala> val x: PartialFunction[Int, Boolean] = { case 0 => true }
x: PartialFunction[Int,Boolean] = <function1>

scala> x.isInstanceOf[Serializable]
res0: Boolean = true