我想将以下代码从 Java 翻译成 Scala:
Foo foo = new Foo() { private static final long serialVersionUID = 12345L; }
Foo
类是一个抽象类。
Scala 中的等效代码是什么样的?
最佳答案
有一个Scala annotation for adding the ID .但是,您似乎无法将此解决方案应用于匿名内部类。然而,根据Scala FAQ :
In Scala private values that evaluate to a constant known at compile-time are turned into private static final Java variables. This undocumented feature should do the trick for you. Just check out the implementation of lists in Scala (see e.g. src/scala/List.java). Both classes :: and Nil have a field serialVersionUID of the following form: private val serialVersionUID = numeric literal;
代码
object Ser extends Application {
trait Foo { def xy: Int }
val x = new Foo with java.io.Serializable { def xy = 2; private val serialVersionUID = 1L }
}
使用 2.8.1 编译器编译良好。我还没有测试它,尽管关于结果类的串行版本是否真的是提供的版本。
关于java - 如何将@SerialVersionUID 添加到匿名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5550249/