24

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)
Elye
  • 53,639
  • 54
  • 212
  • 474
  • 1
    In https://stackoverflow.com/questions/61094618/why-do-data-classes-not-implement-serializable/61109799#61109799 I described some reasons why they aren't and shouldn't be (in my opinion, I don't know any official answers). – Alexey Romanov Apr 16 '20 at 08:56
  • 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. – Elye Apr 16 '20 at 09:26

2 Answers2

30

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)
}
Adam
  • 817
  • 8
  • 16
  • 4
    Or just `println(Foo("") is Serializable)`. – Alexey Romanov Apr 16 '20 at 09:35
  • 9
    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: https://betterprogramming.pub/why-and-how-to-use-kotlins-native-serialization-library-c88c0f14f93d – hannojg Feb 26 '21 at 08:16
  • @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`. – Adam Jun 07 '23 at 15:39
17

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
Zohab Ali
  • 8,426
  • 4
  • 55
  • 63