在scala 2.8中使用scala.collection.JavaConversions._时,scala和java集合之间的自动转换

rjc*_*rjc 2 scala scala-java-interop scala-collections

我有返回此类型的java API:

ArrayList[ArrayList[String]] = Foo.someJavaMethod()   
Run Code Online (Sandbox Code Playgroud)

在scala程序中,我需要将上面的类型作为参数发送到类型为的scala函数"bar"

def bar(param: List[List[String]]) : List[String] = {

}
Run Code Online (Sandbox Code Playgroud)

所以我称之为:

val list = bar(Foo.someJavaMethod())
Run Code Online (Sandbox Code Playgroud)

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

我以为有这个导入

import scala.collection.JavaConversions._ 
Run Code Online (Sandbox Code Playgroud)

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

我也试过用过:

Foo.someJavaMethod().toList 
Run Code Online (Sandbox Code Playgroud)

但这也不起作用.

这个问题的解决方案是什么?

Jea*_*let 7

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

您必须手动映射内部列表.使用隐式转换:

import collection.JavaConversions._
val f = Foo.someJavaMethod()
bar(f.toList.map(_.toList))
Run Code Online (Sandbox Code Playgroud)

或者,更明确地说,如果您愿意:

import collection.JavaConverters._
val f = Foo.someJavaMethod()
bar(f.asScala.toList.map(_.asScala.toList))
Run Code Online (Sandbox Code Playgroud)