gpt4 book ai didi

scala - 伴生对象中的方法编译为 Scala 中的静态方法?

转载 作者:行者123 更新时间:2023-12-04 15:26:04 29 4
gpt4 key购买 nike

看起来 scala 将伴生对象中的方法编译为静态方法,这使得从 Java 代码中调用它们更容易一些。例如,您可以编写 CompanionObject.method() 而不是 CompanionObject$.MODULE$.method()。但是,有时看似无关的代码更改会破坏这种行为。我想出了这个例子来说明问题

$ cat TestCompanion.scala 
class TestCompanion

object TestCompanion {
def init2 {}
}

@SerialVersionUID(1L)
class TestCompanion2

object TestCompanion2 {
def init2 {}
}


$ scalac -version
Scala compiler version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL

$ scalac TestCompanion.scala
$ javap TestCompanion
Compiled from "TestCompanion.scala"
public class TestCompanion extends java.lang.Object implements scala.ScalaObject{
public static final void init2();
public TestCompanion();
}

$ javap TestCompanion2
Compiled from "TestCompanion.scala"
public class TestCompanion2 extends java.lang.Object implements scala.ScalaObject{
public static final long serialVersionUID;
public static {};
public TestCompanion2();
}

所以TestCompanion和TestCompanion2唯一的区别就是后者用@SerialVersionUID注解,init2在TestCompanion中编译成静态方法,而在TestCompanion2中没有。

有人可以解释为什么 scalac 对这两个类的处理方式不同吗?我不明白 @SerialVersionUID 注释应该如何影响静态方法的可用性。

最佳答案

这是一个已知错误:Static forwarders are missing after adding @SerialVersionUID ,由 Josh Cough 提出。从错误描述来看:

In the following code, adding @SerialVersionUID to the class results in the static forwarders missing from the byte code.


object WithoutUID {
val instance = new WithoutUID
}
class WithoutUID extends scala.Serializable

object WithUID {
val instance = new WithUID
}
@SerialVersionUID(0)
class WithUID extends scala.Serializable

Here is the relevant decompiled byte code:


public class WithoutUID implements Serializable, ScalaObject {
public static final WithoutUID instance(){
return WithoutUID.MODULE$.instance();
}
}

public class WithUID implements Serializable, ScalaObject {
public static final long serialVersionUID = 0L;
}

关于scala - 伴生对象中的方法编译为 Scala 中的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923852/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com