Akka remote actors, superclass without default constructor

吃可爱长大的小学妹 提交于 2019-12-05 08:13:24

Things will work if you restructure like so:

trait Foo{
  val a:Int
}
case class MessageFoo(a:Int) extends Foo

I generally try and stay away from class inheritance with case classes. If I need to be able to refer to a set of case classes as an abstract type, I use traits instead.

class A(a: Int)
case class C() extends A(1)

Like cmbaxter's answer points out, this pattern, where the superclass of the case class does not have a no-arg constructor, leads to InvalidClassException on deserialization. Per cmbaxter's answer, avoiding this pattern is one solution.

But what's wrong in this pattern? The reason is documented in the API docs for Serializable:

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

So the problem is that class A does not have a no-arg constructor, plus it is not Serializable. So a simple solution is to make it Serializable!

class A(a: Int) extends Serializable
case class C() extends A(1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!