Cost of adding Serializable?

Is there any cost to tacking on Serializable onto all of my model interfaces? By cost, I mean object size or instantiation speed, etc?

The motivation is to make it so that any model can be added to the Bundle of an Intent to be passed to an activity in an Android app.

For example,

interface Person: Serializable {

    fun getId(): String;

    fun getName(): String;

}

class StdPerson(private val id: String,
                private val name: String): Person {

    override fun getId(): String {
        return this.id;
    }

    override fun getName(): String {
        return this.name;
    }

}

Also, why don’t I have to implement any methods in my class to satisfy the Serializable interface? Does Kotlin do some magic?

Thanks!

You do not need to implement any methods, because that interface does not contain any methods to be implemented: java.io.Serializable.

Also, if I’m reading the documentation right the only runtime cost of implementing this interface is the computation of serial version ID, but only during serialization process and only if it is not explicitly defined by the class itself.

Serializable is a marker interface that lets know Java internals that class could be transformed into binary and back again without loss. There is no runtime overhead for that. On the other hand, one should be careful to add this interface only when he really needs that class to be serialized and is sure that all its members are serializable. Otherwise, one could get a runtime exception in inappropriate moment.

All in all, Java serialization is not exactly the most beautiful Java part. It is old, it is inflexible, it is ugly. I am looking forward to use kotlinx.serialization instead.

Thanks for the responses.

one should be careful to add this interface only when he really needs that class to be serialized and is sure that all its members are serializable.

The second part is easy. All members of my models are serializable.

Can you expand on the first part a bit more? What would be the penalty or possibly problem of adding the Serializable interface to a class when the objects of that class are never actually serialized in the execution of the app?

Thanks!

No penalty. The problem arises when your “Serializable” object contains some references to other objects and depends on the state of the program. Trying to serialize and deserialize it could produce funny results. If it contains only primitives, then everything is OK. Adding unnecessary marker interface will just bloat the code a little.