Scala Java Interoperability
Examples
Converting Scala Collections to Java Collections and vice versa
When you need to pass a collection into a Java method:
import scala.collection.JavaConverters._
val scalaList = List(1, 2, 3)
JavaLibrary.process(scalaList.asJava)
If the Java code returns a Java collection, you can turn it into a Scala collection in a similar manner:
import scala.collection.JavaConverters._
val javaCollection = JavaLibrary.getList
val scalaCollection = javaCollection.asScala
Note that these are decorators, so they merely wrap the underlying collections in a Scala or Java collection interface. Therefore, the calls .asJava and .asScala do not copy the collections.
Arrays
Arrays are regular JVM arrays with a twist that they are treated as invariant and have special constructors and implicit conversions. Construct them without the new keyword.
val a = Array("element")
Now a has type Array[String].
val acs: Array[CharSequence] = a
//Error: type mismatch; found : Array[String] required: Array[CharSequence]
Although String is convertible to CharSequence, Array[String] is not convertible to Array[CharSequence].
You can use an Array like other collections, thanks to an implicit conversion to TraversableLike ArrayOps:
val b: Array[Int] = a.map(_.length)
Most of the Scala collections (TraversableOnce) have a toArray method taking an implicit ClassTag to construct the result array:
List(0).toArray
//> res1: Array[Int] = Array(0)
This makes it easy to use any TraversableOnce in your Scala code and then pass it to Java code which expects an array.