Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Kotlin data class serializable by default?

After knowing Kotlin, love the data class. I could replace Java classes that has equal and hash and toString to it. Most of these Java classes are serializable class. So my question is, when we convert to data class, do I still need to make it serializable explicitly? like

data class SomeJavaToKotlinClass(val member: String) : Serializable

Or it is okay to be

data class SomeJavaToKotlinClass(val member: String)
like image 611
Elye Avatar asked Apr 16 '20 01:04

Elye


People also ask

Is Kotlin data class serializable?

Modeling Data. The Kotlin Serialization library generates serializers for classes annotated with @Serializable . A serializer is a class that handles an object's serialization and deserialization. For every class annotated with @Serializable , the compiler generates a serializer on its companion object.

Is Kotlin list serializable?

The simple data classes Pair and Triple from the Kotlin standard library are serializable.

How does Kotlin data class work?

Data classes specialize in holding data. The Kotlin compiler automatically generates the following functionality for them: A correct, complete, and readable toString() method. Value equality-based equals() and hashCode() methods.


2 Answers

No, Kotlin data classes do not implicitly implement this interface. You can see from this example:

import java.io.Serializable

data class Foo(val bar: String)

fun acceptsSerializable(s: Serializable) { }

fun main(args: Array<String>) {
    val f: Foo = Foo("baz")
    acceptsSerializable(f)  // Will not compile
}
like image 160
Adam Avatar answered Oct 25 '22 21:10

Adam


I had to add : Serializable at the end of class to make is Serializable. Just like this

class SizeVariantModel (val price: Double, val discountedPrice: Double?) : Serializable
class ColorVariantModel (val name: String, val colorCode: String) : Serializable

I also had to import Serializable

import java.io.Serializable
like image 33
Zohab Ali Avatar answered Oct 25 '22 19:10

Zohab Ali