如何将嵌套的scala集合转换为嵌套的Java集合 [英] How to convert a nested scala collection to a nested Java collection
问题描述
我的Java代码需要一个
java.util.Map< Double,java.lang.Iterable< Foo>>
我的scala代码有一个
Map [Double,Vector [Foo]]
错误:
错误:type mismatch;
found:scala.collection.immutable.Map [scala.Double,Vector [Foo]
required:java.util.Map [java.lang.Double,java.lang.Iterable [Foo]]
似乎scala.collection.JavaConversions不适用于嵌套集合,即使Vector可以是暗中转换为Iterable。
scala.collection.JavaConversions
应该被弃用恕我直言。您最好通过使用 scala.collection.JavaConverters
来明确转换发生的位置和时间。在你的情况下:
$ p $ import scala.collection.JavaConverters._
type Foo = Int //只需要编译
val scalaMap = Map(1.0 - > Vector(1,2))//作为示例
val javaMap = scalaMap.map {
case (d,v)=> d - > v.toIterable.asJava
} .asJava
I'm having compilation issues between Scala and Java.
My Java code needs a
java.util.Map<Double, java.lang.Iterable<Foo>>
My scala code has a
Map[Double, Vector[Foo]]
I get the compilation error:
error: type mismatch;
found : scala.collection.immutable.Map[scala.Double,Vector[Foo]
required: java.util.Map[java.lang.Double,java.lang.Iterable[Foo]]
It seems the scala.collection.JavaConversions don't apply to nested collections, even though a Vector can be implictly converted to an Iterable. Short of iterating through the scala collection and doing the conversion by hand, is there something I can do to make the types work?
scala.collection.JavaConversions
should be deprecated IMHO. You are better off being explicit about where and when the conversion happens by using scala.collection.JavaConverters
. In your case:
import scala.collection.JavaConverters._
type Foo = Int // Just to make it compile
val scalaMap = Map(1.0 -> Vector(1, 2)) // As an example
val javaMap = scalaMap.map {
case (d, v) => d -> v.toIterable.asJava
}.asJava
这篇关于如何将嵌套的scala集合转换为嵌套的Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!