如何在 Kotlin 中实现 Serializable 使其也适用于 Java?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50897540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:51:54  来源:igfitidea点击:

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

javaserializationkotlin

提问by GlenPeterson

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":

我有一些在 Java 中使用多年的代码,但在 Kotlin 中需要它(它的接口扩展了集合接口)。有些类是可序列化的。当我尝试显而易见的事情时,我得到“无法访问 'Serializable':它在 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?

那么,我是只导入 java.io.Serializable,还是会导致其他问题?

采纳答案by Alexey Romanov

do I just import java.io.Serializable

我只是导入 java.io.Serializable

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

是的。请注意,Kotlin 使用@Transient注释而不是关键字。

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...

当然,Java 序列化确实有其问题,但 Kotlin 和 Java 在这方面没有区别,如果您对当前的代码感到满意……