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 myScanner.`match`.
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.
What about using Scala parameterized types in Java? Consider the following JUnit 4 test, which uses scala.collection.mutable.LinkedHashMap and scala.Option. It shows some of the idiosyncrasies ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access