How can I convert a java 1.4 Collection to a Scala Seq?
I am trying to pass a java-collection to a scala method:
import scala.collection.JavaConversions._ // list is a 1.4 java.util.ArrayList // repository.getDir is Java legacy code val list = repository.getDir(...) perform(list) def perform(entries: ListSVNDirEntry) = ...
I always receive this error:
type mismatch; found : java.util.Collection?0 where type ?0 required: List SVNDirEntry
So I guess I have to create the parameterized Sequence myself as Scala is only able to create an unparameterized Iterable?
First you have to make sure that
list has the type
java.util.ListSVNDirEntry. To do this, use a cast:
After that, the implicit conversion will be resolved for you if you import the
JavaConversions object. An implicit conversion to a Scala sequence exists in the
JavaConversions object. See the following example with a list of strings being passed to a method that expects a Scala sequence:
scala> val jvlist: java.util.List_ = new java.util.ArrayListString jvlist: java.util.List_ = scala> jvlist.asInstanceOfjava.util.ListString res0: java.util.ListString = scala> import collection.JavaConversions._ import collection.JavaConversions._ scala> def perform(scalaseq: SeqString) = println("ok") perform: (scalaseq: scala.collection.SeqString)Unit scala> perform(res0) ok
These conversions do not copy the elements – they simply construct a wrapper around a Java collection. Both versions point to the same underlying data. Thus, there is no implicit conversion in
JavaConversions to immutable Scala lists from mutable Java lists, because that would enable changing the contents of a Scala collection that is guaranteed to be immutable.
In short – prefer
List... when defining parameters for methods if you can live with a less specific interface (as in
perform above). Or write your own function that does the conversion by copying the elements.
You have to cast the legacy collection down to the target type. Something along the lines of: