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
andsubstringofString, which is a class defined in Java. It
also accesses the staticoutfield of the Java classSystem, and
invokes its (overloaded)printlnmethod. 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?
I think you might be blinded by Java assumptions. Consider this simple snippet of code:
The means that the method
Yis being called on the objectX, or on some other object whichXwas 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
Xwill 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:
will work if
Xis a Scala singleton object, but won’t work if it is a Java class with static members.