Kotlin

Kotlin

Made by DeepSource

Declaration of serialVersionUID not found KT-W1060

Anti-pattern
Major

When a class implements Serializable, it is recommended to also declare a serialVersionUID field within that class. The serialVersionUID serves as a version identifier for the serialized class. It helps to ensure compatibility between the serialized objects and their corresponding class definitions, particularly when performing deserialization.

The serialVersionUID field is a unique identifier that acts as a version control mechanism. It helps to verify that the serialized object being deserialized matches the version of the class present at runtime. If the serialVersionUID of the serialized object does not match the serialVersionUID of the class being used for deserialization, an InvalidClassException may be thrown, indicating a mismatch between the serialized object and the class definition.

Bad Practice

class IncorrectSerializable : Serializable {
    // No mention of `serialVersionUID` anywhere in the class
}

class IncorrectSerializable : Serializable {
    companion object {
        val serialVersionUID = 1 // wrong declaration for UID
    }
}

Recommended

If the class implements Serializable, explicitly declare the serialVersionUID field.

class CorrectSerializable : Serializable {
    companion object {
        const val serialVersionUID = 1L
    }
}

References