views:

226

answers:

4

I'm trying to use some Scala code and am having a hard time figuring out how to convert the Scala lists into standard Java lists.

Any ideas?

+2  A: 

Fighting Scala – Scala to Java List Conversion « Stubbisms ...

http://stubbisms.wordpress.com/2009/02/18/fighting-scala-scala-to-java-list-conversion/

Nabble - Scala - User - Type mismatch: cannot convert from ...

http://old.nabble.com/Type-mismatch:-cannot-convert-from-Iterable%3CFile%3E-to-Iterable%3CFile%3E-td20322743.html

ratty
+5  A: 

Scala List and Java List are two different beasts, because the former is immutable and the latter is mutable. So, to get from one to another, you first have to convert the Scala List into a mutable collection.

On Scala 2.7:

import scala.collection.jcl.Conversions.unconvertList
import scala.collection.jcl.ArrayList
unconvertList(new ArrayList ++ List(1,2,3))

On Scala 2.8:

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
asList(ListBuffer(List(1,2,3): _*))
val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)

However, asList in that example is not necessary if the type expected is a Java List, as the conversion is implicit, as demonstrated by the last line.

Daniel
+5  A: 

You might want to consider using Jorge Ortiz's Scala-JavaUtils (http://github.com/jorgeortiz85/scala-javautils).

ams
+1  A: 

For single invocations, doing it by hand might be the simplest solution:

val slist = List (1, 2, 3, 4)          
val jl = new java.util.ArrayList [Integer] (slist.size)
slist.foreach (jl.add (_))   

I didn't measure performance.

Stefan W.