Can you override the stream writers in scala @serializable objects?

前端 未结 2 2058
栀梦
栀梦 2020-12-29 13:39

I now understand that scala @serializable objects can be used the same as a Java Serializable object. In a Java Serializable object there are methods you can override to ch

相关标签:
2条回答
  • 2020-12-29 13:57

    Yes, you can use the same methods in Scala as in Java:

    @throws(classOf[IOException])
    private def writeObject(out: ObjectOutputStream): Unit = // ...
    
    @throws(classOf[IOException])
    private def readObject(in: ObjectInputStream): Unit = // ...
    
    0 讨论(0)
  • 2020-12-29 14:00

    As already stated, you can define your own writeObject and readObject methods.

    @throws(classOf[java.io.IOException])
    private def writeObject(out : java.io.ObjectOutputStream) : Unit = /* your definition  here */
    

    However be careful when performing this on nested classes, objects or traits.

    @serializable class Foo(x : Int) { @serializable object X { def y = x } }

    If I serialize object X, it will actually serialize the containing Foo class, so this must also be serializable. This can be a PITA to deal with in custom serialization methods, so here's fair warning.

    Another pain-point can be closure serialization. Try to keep a mental model of what variables are being captured in serialized closures. Ensure that these variables are something you'd want sent over IO!

    0 讨论(0)
提交回复
热议问题