When using the -Xcheckinit compiler option and implementing my own readObject method in a serializable class, I can't call any accessor functions on fields declared in the body of my class from the readObject method. Fields declared as constructor arguments are ok. When I do try to access a field declared in the class body, I get a scala.UninitializedFieldError.
That is, the following code fails on println(y)
in the readObject method, even after y has been set in the previous line!
@serializable case class XYPointWithRWAndPrint(var x: Int) {
var y = 0
@throws(classOf[java.io.IOException])
private def writeObject(out: java.io.ObjectOutputStream) {
out.writeInt(x)
out.writeInt(y)
}
@throws(classOf[java.io.IOException])
@throws(classOf[ClassNotFoundException])
private def readObject(in: java.io.ObjectInputStream) {
x = in.readInt()
println(x)
y = in.readInt()
println(y)
}
}
Why?