Chapter 3Java Compatibility

Right from the start, the creators of Scala took the Java compatibility issue very seriously. This makes a lot of sense, given all of the already existent Java libraries that are out there.

This chapter starts by showing you how to convert Java collections to Scala and vice versa. It covers how Scala traits relate to Java interfaces, and details how both things can cooperate. Java enums are then mapped into the Scala world. You'll see that, in Scala, you have more than one alternative.

SCALA AND JAVA COLLECTIONS

Collections are probably one of the more used APIs, both in Scala and Java. When interoperating with a Java library it's important to know how you can go from a Java collection to a Scala one and back again.

In the scala.collection package, there are two objects that can be used for this purpose, namely JavaConversions and JavaConverters.

The former provides a bunch of implicit conversions supporting interoperability between Scala and Java collections. For example, Java's List does not have a map method, but you can still call map on it thanks to the implicit conversion into ArrayBuffer:

import java.util.{ArrayList => JArrayList, List => JList} import scala.collection.JavaConversions._ import scala.collection.mutable val javaList: JList[Int] = new JArrayList() ...

Get Professional Scala 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.