我有返回此类型的Java API:

ArrayList[ArrayList[String]] = Foo.someJavaMethod()

在scala程序中,我需要将上述类型作为参数发送给类型为
def bar(param: List[List[String]]) : List[String] = {

}

所以我这样称呼吧:
val list = bar(Foo.someJavaMethod())

但这不起作用,因为我得到了编译错误。

我以为有导入
import scala.collection.JavaConversions._

将在Java和Scala集合之间进行隐式自动转换。

我也尝试使用像:
Foo.someJavaMethod().toList

但这也不起作用。

这个问题有什么解决方案?

最佳答案

首先,ArrayList不会转换为List,而是会转换为Scala Buffer。其次,隐式转换不会递归到集合的元素中。

您必须手动映射内部列表。包含隐式转换:

import collection.JavaConversions._
val f = Foo.someJavaMethod()
bar(f.toList.map(_.toList))

或者,更明确地说,如果您愿意:
import collection.JavaConverters._
val f = Foo.someJavaMethod()
bar(f.asScala.toList.map(_.asScala.toList))

关于scala - 在Scala 2.8中使用scala.collection.JavaConversions._时,在scala和Java集合之间进行自动转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6609892/

10-13 07:54
查看更多