Using Java Collections in Scala 2.8 (and 2.7)

From:
andrew cooke <andrew@...>

Date:
Fri, 9 Oct 2009 18:10:57 -0400

If you want to inter-operate with Java objects that use the Java
collections it's not immediately clear what to do - the Scala
collections are completely separate.
However, it turns out that's there's a solution that requires almost
no typing and replies on Scala's implicit conversions. All that is
necessary in 2.8 is to add
import scala.collection.JavaConversions._
and the inter-operation will happen "magically". In practice, I think
that Scala's type system uses classes from that package to convert
from one type to another (so it automatically wraps a Scala mutable
set, for example, in something that implement's Java's AbstractSet
interface).
In 2.7 there appears to be a similar solution, in
scala.collection.jcl.Convertions, but that package has disappeared in
2.8. It also contains collections that were "backed" by Java
collections (and again that has disappeared in 2.8).
For example, here's some code of mine:
import scala.collection.JavaConversions._
import scala.collection.mutable.HashSet
...
val commands = new HashSet[Command]()
commands.addAll(List[Command](
new Command("lastfm artist <name:string>",
...
commands.add(new HelpCommand(commands))
The HelpCommand in the last line above requires a Java HashSet, so the
Scala instance is automatically converted.
Note that there are only wrappers for the mutable collections.
Andrew