In scala.collection
, there are two very similar objects JavaConversions
and JavaConverters
.
- What is the difference between these two objects?
- Why do they both exist?
- When do I want to use one vs. the other?
In scala.collection
, there are two very similar objects JavaConversions
and JavaConverters
.
For anyone landing on this question since Scala 2.12.x,
JavaConversions
is now deprecated andJavaConverters
is the preferred method.JavaConversions
provide a series of implicit methods that convert between a Java collection and the closest corresponding Scala collection, and vice versa. This is done by creating wrappers that implement either the Scala interface and forward the calls to the underlying Java collection, or the Java interface, forwarding the calls to the underlying Scala collection.JavaConverters
uses the pimp-my-library pattern to “add” theasScala
method to the Java collections and theasJava
method to the Scala collections, which return the appropriate wrappers discussed above. It is newer (since version 2.8.1) thanJavaConversions
(since 2.8) and makes the conversion between Scala and Java collection explicit. Contrary to what David writes in his answer, I'd recommend you make it a habit to useJavaConverters
as you'll be much less likely to write code that makes a lot of implicit conversions, as you can control the only spot where that will happen: where you write.asScala
or.asJava
.Here's the conversion methods that
JavaConverters
provide:To use the conversions directly from Java, though, you're better off calling methods from
JavaConversions
directly; e.g.:As explained in the API,
JavaConversions
is a set of implicit conversions that transforms java collections into related scala collection.You can use it with an
import collection.JavaConversions._
. When necessary, the compiler will automatically transform the java collection into the right scala type.JavaConverters
are a set of decorator that helps transform java or scala collections to scala or java collections usingasScala
orasJava
methods that will be implicitly added to the collection that you want to transform. In order to use these converters, you need to import :You should prefer
JavaConversions
as it's generally easier to use (no need to useasScala
orasJava
).