Wednesday, September 16, 2009

converting Java collections to scala collections

This took me many hours to figure out. I didn't find a word about it in the (quite a bit of) stuff I read, including the "Programming in Scala" book, blogs, posts etc.

How to best convert java collections into scala collections and back. This is crucial, as lots of would-be scalaistas would still carry around some kind of Java library, be it JNDI or JTA or some in-house non-rewritables!

As of scala 2.7, scala.collection.jcl.Convertions is your friend. As of scala 2.8, scala.collection.JavaConversions is your best friend. Enough said.

Interestingly, I use List pretty much everywhere in my code. However, as you'll see, since List is the only one that doesn't freely convert from one to the other, it follows that you should use Seq[A] in all your scala code...hmmmm

[later edit] Also, your arguably best friend in scala is the scala.collections.mutable.ListBuffer - check it out, it's all you thought List would be! Although, after a while, you will find yourself relying on mutable collections less and less...

To get the full power of the implicit java to scala conversions, make sure you import the contents of the class, note the underscore below:
import scala.collection.JavaConversions._
[Later edit] I removed my examples here as being too clumsy :) use the import above instead.
blog comments powered by Disqus