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: List[SVNDirEntry]) = ...
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
listhas the typejava.util.List[SVNDirEntry]. To do this, use a cast:After that, the implicit conversion will be resolved for you if you import the
JavaConversionsobject. An implicit conversion to a Scala sequence exists in theJavaConversionsobject. See the following example with a list of strings being passed to a method that expects a Scala sequence: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
JavaConversionsto 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
Seq[...]toList[...]when defining parameters for methods if you can live with a less specific interface (as inperformabove). Or write your own function that does the conversion by copying the elements.