Why do data classes not implement Serializable?

﹥>﹥吖頭↗ 提交于 2020-06-16 02:48:26

问题


I am new to kotlin but a veteran of scala. The former has impressed me so far. But at this moment I am working through a head scratcher - that the data class does not implement Serializable. How a class with that name could expected to not be routinely expected to be used in that manner eludes me.

What are the technical challenge(s) that precluded that support? I'm interested because i'd like to create a wrapper. It seems that the expectation is to always provide a serializer() ? That is cumbersome and actually kotlinx.serialization is not working for me yet - even after some effort.


回答1:


It is a bit unclear from the question if you mean java.io.Serializable (based on the analogy with Scala and "implement") or kotlinx.serialization.Serializable (based on the second paragraph and discussion in the comments).

First, for the Java one:

I think the way you should phrase it is: why do data classes not implement Serializable by default? You can always add : Serializable if you want.

Then you can note this isn't the only place where Kotlin requires you to be more explicit than Scala. For another data class example, you need to mark properties by val or var where Scala assumes val by default. And for non-data classes, Scala allows you to use non-val constructor parameters inside the class effectively promoting them to private val where Kotlin doesn't.

For Serializable in particular:

  1. It would privilege Java serialization which has bad reputation (as mentioned in the comments already).

  2. Serializable isn't usable in cross-platform (or just Kotlin/JS or Kotlin/Native) projects. Maybe data classes could only be serializable on JVM, but it would be an unnecessary mismatch between platforms.

  3. case classes implement Serializable even if they have non-Serializable properties and will throw if you actually try to serialize them.

  4. In the common case of multiple case classes extending a trait, if you forget to make the trait extends Product with Serializable type inference often gives ugly types.

For Kotlin Serialization, the answer is even simpler: you don't want a basic language feature like data classes to depend on an experimental and immature library. I wouldn't be surprised if data classes do become @Serializable by default when it "graduates" like coroutines did in 1.3.



来源:https://stackoverflow.com/questions/61094618/why-do-data-classes-not-implement-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!