Convert java.util.Set to scala.collection.Set
How can I convert a java.util.Set[String] to a scala.collection.Set with a generic type in Scala 2.8.1?
import scala.collection.JavaConversions._
var in : java.util.Set[String] = new java.util.HashSet[String]()
in.add("Oscar")
in.add("Hugo")
val out : scala.collection.immutable.Set[String] = Set(in.toArray : _*)
And this is the error message
<console>:9: error: type mismatch;
found : Ar开发者_开发技巧ray[java.lang.Object]
required: Array[_ <: String]
val out : scala.collection.immutable.Set[String] = Set(javaset.toArray : _*)
What am I doing wrong?
Use JavaConverters instead
import scala.collection.JavaConverters._
val out = in.asScala
out: scala.collection.mutable.Set[String] = Set(Hugo, Oscar)
toArray()
called on a java Set
will return an array of Object
. Since you already imported JavaConversions
, asScalaSet
will implicitly convert your Java set to a mutable Scala set or use toSet
to convert it to an immutable set.
See also Convert Scala Set into Java (java.util.Set)
精彩评论