Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement Serializable in Kotlin so it also works in Java?

I have some code that I've been using for years in Java, but need it in Kotlin (its interfaces extend collections interfaces). Some classes are serializable. When I try the obvious, I get "Cannot access 'Serializable': it is internal in kotlin.io":

class Foo(val someField:Int): Serializable {
    companion object {
        private const val serialVersionUID = 20180617104400L
    }
}

So, do I just import java.io.Serializable, or will that cause other issues?

like image 782
GlenPeterson Avatar asked Jun 17 '18 14:06

GlenPeterson


People also ask

Can kotlin data class be serializable?

Kotlin Serialization supports multiple formats, including JSON and Protocol Buffers. In this example, we'll continue with JSON. In order to read and write your data class to JSON using Kotlin serialization, you need to annotate your data class with @Serializable and override the Serializer's writeTo() and readFrom() .

What happens if we implement serializable interface in Java?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.


1 Answers

do I just import java.io.Serializable

Yes. Just be aware that Kotlin uses @Transient annotation instead of a keyword.

Of course, Java serialization does have its issues, but there's no difference in that respect between Kotlin and Java, and if you are happy with your current code...

like image 93
Alexey Romanov Avatar answered Oct 22 '22 06:10

Alexey Romanov