Scala convert List[Int] to a java.util.List[java.lang.Integer]

Pandora Lee picture Pandora Lee · Aug 9, 2011 · Viewed 15.8k times · Source

Is there a way in Scala to convert a List[Int] to java.util.List[java.lang.Integer]?

I'm interfacing with Java (Thrift).

JavaConversions supports List --> java.util.List, and implicits exist between Int --> java.lang.Integer, but from what I can tell I would still need an extra pass to manually do the conversion:

val y = List(1)     
val z: java.util.List[Integer] = asList(y)  map { (x: Int) => x : java.lang.Integer }

Answer

paradigmatic picture paradigmatic · Aug 9, 2011

Apparently you need both conversions. However, you can group them in a single implicit conversion:

implicit def toIntegerList( lst: List[Int] ) =
  seqAsJavaList( lst.map( i => i:java.lang.Integer ) )

Example:

scala> def sizeOf( lst: java.util.List[java.lang.Integer] ) = lst.size

scala> sizeOf( List(1,2,3) )
res5: Int = 3