Java static class members and Scala interoperability

泄露秘密 提交于 2021-02-07 21:54:20

问题


From the An Overview of the Scala Programming Language, Second Edition:

// Scala
object PrintOptions {
    def main(args: Array[String]): Unit = {
        System.out.println("Options selected:")
        for (val arg <- args)
            if (arg.startsWith("-"))
                System.out.println(" " + arg.substring(1))
    }
}

In the example above, the Scala program invokes methods startsWith and substring of String, which is a class defined in Java. It also accesses the static out field of the Java class System, and invokes its (overloaded) println method. This is possible even though Scala does not have a concept of static class members. In fact, every Java class is seen in Scala as two entities, a class containing all dynamic members and a singleton object, containing all static members.

I understand translation of Scala's companion objects into Java bytecode, but I am not sure what exactly does it means bold text in upper blockquote "is seen in Scala" for opposite example (from Java to Scala).

Does it mean that Java classes with static members are actually converted or just interpreted as two entities in Scala? Or both of my assumptions are wrong?


回答1:


I think you might be blinded by Java assumptions. Consider this simple snippet of code:

X.Y()

The means that the method Y is being called on the object X, or on some other object which X was implicitly converted into.

Maybe that doesn't look surprising, or you don't see anything amiss with that, so let's state explicitly a consequence: X will NEVER be a class. You don't invoke methods on classes, period.

Naturally, that presents a serious interoperability problem with Java regarding static members, and that's why it is stated that static members of a Java class X will be "seen" as a singleton object: because, otherwise, you'll never be able to use them.

Note that Scala's singleton objects are true objects -- they are instances of singleton classes. Java classes with static members will not give origin to single objects, though. In practice, this means that this line:

val x = X

will work if X is a Scala singleton object, but won't work if it is a Java class with static members.




回答2:


It simply means that scala doesn't change anything to the initial java code, where static members and non-static members are in the same class.

Thus your second assumption is true, the first one is false.

I guess the book use seen instead of interpreted because this last one can have a different meaning if you think about "interpreted languages" (which are meaningless in that context).



来源:https://stackoverflow.com/questions/9906143/java-static-class-members-and-scala-interoperability

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