Does kotlinx.serialization handle class versions?

Viewed 265

With Java serialization, there was serialVersionUID. I don't know how well that worked, but it was, at least, a simple mechanism for testing whether a class changed between serialization and deserialization. Does kotlinx.serialization have any such mechanism for matching the version of the class that was serialized with the current one (such as, maybe, a checksum or hashcode of the SerialDescriptor)? If not, is there a recommended best practice for avoiding this class of bugs?

1 Answers

It doesn't seem like serialVersionUID is a mechanism to track changes. Instead, it is a mechanism to fail deserialization early if there is a version mismatch:

If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.

kotlinx.serialization fails depending on the specific encoder/decoder, and how it is configured. For example, Json can be configured to fail on unexpected fields, or ignore them silently.

You will get runtime serialization exceptions if the serial descriptors do not match the expected serialized data; so some of the serialization logic would have run, but it would still fail.

The question is thus what you hope to achieve. If you want to fail early (not certain why that would be a benefit), you could probably write a custom serializer which includes a hashcode based on information contained in SerialDescriptor as you suggest.

Practically speaking, you are probably better off applying some versioning elsewhere in the system, such as in a wrapper which determines the version of the payload.

Related