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 ...
Get Programming Scala, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.