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

2

10

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 change how the object streams: writeObject(ObjectOutputStream) / readObject(ObjectOutputStream).

Can you override or inject methods into a scala @serializable object allowing you to change how the object serializes?

Virago answered 9/8, 2010 at 19:7 Comment(1)
Thanks! I was getting the signature of the method wrong.Virago
S
10

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 = // ...
Stenophyllous answered 9/8, 2010 at 19:59 Comment(3)
readObject returns Unit. What is an example implementation that makes an object? Given that it is a method on the instance? The examples in java all call this.someProperty to assign values. How does this work in scala with immutable vals on case classes?Miru
@ScottSmith I suspect you're stuck using mutable fields or some really nasty reflection tricks.Stenophyllous
@ScottSmith ... or maybe employ the writeReplace and readResolve methods.Stenophyllous
R
3

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!

Rescript answered 11/8, 2010 at 1:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.