How to convert collections from Scala to Java?

Use case

Very often, while we are writing in Scala, we use Java libraries. There are tons of them and they are usually great. The only problem may be when we want to use some methods from such libraries that expects Java collection type, while we already have Scala collection objects in our project.

Solution

There are two extremely useful objects in scala.collection package, which will help us to achieve our goal. They are JavaConverters and JavaConversions. What the do and when to choose what?

Control your code

As everything — it depends. It depends on how you want to control your code.

1. If you want to be explicit and tell exactly what you want to convert:

2. If you don’t want co control conversions and let compiler make implicit work for you:

Aliases

An extra feature to reduce name clashes is to use type aliasing. For example, Scala already has a number of things named Map. If you are using a Java API expecting a java.util.Map, you are likely to get name conflict. For Java, you would probably fully qualified class name, e.g. java.util.Map, and you can do the same in Scala, but that’s verbose. With renaming, you can write things like:

import java.util.{ Map ⇒ JMap, List ⇒ JList }

And then use the Java Map as JMap and the Java List as JList. Nothing is changed at the VM level: it’s the same classes, but you now have a nice, short alias for them in the scope of the imports.

Summary

That’s it. So simple to understand and easy to implement. You can always dive into source to see what is happening under the hood.

Resources