Is Kotlin data class serializable by default?
Asked Answered
S

3

28

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)
Sarinasarine answered 16/4, 2020 at 1:15 Comment(2)
In #61095118 I described some reasons why they aren't and shouldn't be (in my opinion, I don't know any official answers).Kamakura
Nice one. Thanks @AlexeyRomanov. That's a very nice explanation. I think my question is valid as the fact that data class implement all the function that is required by serialization will cause user like me to assume that's what it has by default. But glad to know the exact answer.Sarinasarine
M
32

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")
    
    // The following line produces the compiler error:
    // Type mismatch: inferred type is Foo but Serializable was expected
    acceptsSerializable(f)
}
Maidenhead answered 16/4, 2020 at 2:8 Comment(3)
Or just println(Foo("") is Serializable).Kamakura
For anyone looking at how to serialize a data class if it doesn't work by default, have a look at the kotlinx-serialization plugin. With this, you can just put @Serializable to your data class and its serializable. This article sums it up really well: betterprogramming.pub/…Reseau
@AlexeyRomanov True, but it will also not compile with the error Incompatible types: Serializable and Foo. The example in the answer returns the error Type mismatch: inferred type is Foo but Serializable was expected.Maidenhead
B
22

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
Busch answered 16/11, 2021 at 14:4 Comment(1)
Thanks for the import. Android Studio wasn't suggesting it :·)Omen
C
0

do this : @Serializable public data class Level(....

import: import kotlinx.serialization.Serializable

Chandless answered 20/6, 2024 at 13:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.