Section 29.1 Chapter 29 · Combining Scala and Java 595
To make this happen required an occasional hard choice in the design of
Scala. For example, it might have been nice to resolve overloaded methods
at run time, using run-time types, rather than at compile time. Such a design
would break with Java’s, however, making it much trickier to mesh Java
and Scala. In this case, Scala stays with Java’s overloading resolution, and
thus Scala methods and method calls can map directly to Java methods and
method calls.
For other features Scala has its own design. For example, traits have no
equivalent in Java. Similarly, while both Scala and Java have generic types,
the details of the two systems clash. For language features like these, Scala
code cannot be mapped directly to a Java construct, so it must be encoded
using some combination of the structures Java does have.
For these features that are mapped indirectly, the encoding is not fixed.
There is an ongoing effort to make the translations as simple as possible, so
by the time you read this, some details may be different than at the time of
writing. You can find out what translation your current Scala compiler uses
by examining the “.class” files with tools like javap.
Those are the general rules. Consider now some special cases.
Value types
A value type like Int can be translated in two different ways to Java. When-
ever possible, the compiler translates a Scala Int to a Java int to get better
performance. Sometimes this is not possible, though, because the compiler
is not sure whether it is translating an Int or some other data type. For ex-
ample, a particular List[Any] might hold only Ints, but the compiler has no
way to be sure.
In cases like this, where the compiler is unsure whether an object is a
value type or not, the compiler uses objects and relies on wrapper classes.
Wrapper classes such as, for example, java.lang.Integer allow a value
type to be wrapped inside a Java object and thereby manipulated by code
that needs objects.
1
Singleton objects
Java has no exact equivalent to a singleton object, but it does have static
methods. The Scala translation of singleton objects uses a combination of
1
The implementation of value types was discussed in detail in Section 11.2.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index