Can you override stream entries in scala @serializable objects?

Now I understand that scala @serializable objects can be used just like a Java Serializable object. There are methods in the Java Serializable that you can override to modify object streams: writeObject (ObjectOutputStream) / readObject (ObjectOutputStream).

Can you override or introduce methods in a scala @serializable object, allowing you to change how the object is serialized?

+7
scala serialization serializable
source share
2 answers

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 = // ... 
+8
source share

As already mentioned, 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 doing this on nested classes, objects, or traits.

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

If I serialize an X object, it actually serializes the containing class Foo, so it must also be serializable. It could be PITA to deal with the usual serialization methods, so here is a fair warning.

Another point of pain may be serialization closure. Try to maintain a mental model of which variables are captured in serialized closures. Make sure these variables are what you want to send via IO!

+3
source share

All Articles