Why Scala can serialize Function but not PartialFunction?

后端 未结 1 1338
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 08:27

I have 2 functions (1 of them is partial) defined similarly under an object:

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


        
相关标签:
1条回答
  • 2021-01-22 09:03

    Because you are explicitly creating AbstractPartialFunction without extending Serializable. If you do the same with new AbstractFunction1[String, Int] { ... }, it also won't be serializable. On the other hand, when you use the anonymous function syntax, the compiler generates a class which does extend Serializable. This includes anonymous partial function syntax:

    scala> val x: PartialFunction[Int, Boolean] = { case 0 => true }
    x: PartialFunction[Int,Boolean] = <function1>
    
    scala> x.isInstanceOf[Serializable]
    res0: Boolean = true
    
    0 讨论(0)
提交回复
热议问题