Chapter 22. Java Interoperability
Of all the alternative JVM languages, Scala’s interoperability with Java source code is among the most seamless. This chapter begins with a discussion of interoperability with code written in Java.
Because Scala syntax is primarily a superset of Java syntax, invoking Java code from Scala is usually straightforward. Going the other direction requires that you understand how some Scala features are encoded in byte code while still satisfying the JVM specification. We discuss several of the interoperability issues here.
Using Java Names in Scala Code
Java’s rules for type, method, field, and variable names are more restrictive than Scala’s rules. So, in almost all cases, you can just use the Java names in Scala code. You can create new instances of Java types, call Java methods, and use Java variables and instance fields.
The exception is when a Java name is actually a Scala keyword. As we saw in “Reserved Words”, “escape” the name with single back ticks. For example, consider the
match keyword in Scala and the
match method on
java.util.Scanner. Call the latter with
Java and Scala Generics
All along, we’ve been using Java types in Scala code, like
java.lang.String. You can even use Java generic classes, such as Java collections in Scala.