Mark Needham

Thoughts on Software Development

Scala: Converting a scala collection to java.util.List

with 3 comments

I’ve been playing around a little with Goose – a library for extracting the main body of text from web pages – and I thought I’d try converting some of the code to be more scala-esque in style.

The API of the various classes/methods is designed so it’s interoperable with Java code but in order to use functions like map/filter we need the collection to be a Scala one.

That’s achieved by importing ‘scala.collections.JavaConversions._’ which will apply an implicit conversion to convert the Java collection into a Scala one.

I needed to go back to the Java one again which can be achieved with the following code:

import scala.collection.JavaConversions._
 
val javaCollection = seqAsJavaList(Seq("abc"))

I also used that function in the StopWords.scala object in Goose.

There are a load of other functions available in JavaConversions as well for going to a Dictionary, Map, Set and so on.

Be Sociable, Share!

Written by Mark Needham

February 5th, 2012 at 9:40 pm

Posted in Scala

Tagged with

  • Satish Srinivasan

    Use of JavaConversions violates Jorge’s laws (http://dl.dropbox.com/u/1679797/Scalathon/CanBeConfusing.pdf) – I believe it’s better form to use JavaConverters instead.

  • As in this –¬†http://www.scala-lang.org/api/current/scala/collection/JavaConverters$.html? So does that mean you’d just need to import the package into the class and the conversion would be done implicitly?

  • Satish Srinivasan

    No – JavaConversions does it implicitly (which’s confusing bad magic); with JavaConverters, it’s an explicit conversion by calling asJava or asScala!