17.1. Going to and from Java Collections

Problem

You’re using Java classes in a Scala application, and those classes either return Java collections, or require Java collections in their method calls.

Solution

Use the methods of Scala’s JavaConversions object to make the conversions work.

For instance, the java.util.ArrayList class is commonly used in Java applications, and you can simulate receiving an ArrayList from a method in the REPL, like this:

scala> def nums = {
     |   var list = new java.util.ArrayList[Int]()
     |   list.add(1)
     |   list.add(2)
     |   list
     | }
nums: java.util.ArrayList[Int]

Even though this method is written in Scala, when it’s called, it acts just as though it was returning an ArrayList from a Java method:

scala> val list = nums
list: java.util.ArrayList[Int] = [1, 2]

However, because it’s a Java collection, I can’t call the foreach method on it that I’ve come to know and love in Scala, because it isn’t there:

scala> list.foreach(println)
<console>:10: error:
value foreach is not a member of java.util.ArrayList[Int]
              list.foreach(println)
                   ^

But by importing the methods from the JavaConversions object, the ArrayList magically acquires a foreach method:

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> list.foreach(println)
1
2

This “magic” comes from the power of Scala’s implicit conversions, which are demonstrated in Recipe 1.10.

Discussion

When you get a reference to a Java collections object, you can either use that object as a Java collection ...

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