![](/img/trans.png)
[英]Convert from scala.collection.Seq<String> to java.util.List<String> in Java code
[英]How to convert scala.collection.immutable.List[scala.collection.mutable.MutableList[String]] to java.util.List[java.util.List[String]]
我在Java类中使用了Scala方法,并抛出以下错误。 由于某种原因,隐式转换不适用于List
of Lists
但确实适用于List
。 (例如: mutable.MutableList
到util.List
)
Error:(124, 143) type mismatch;
found: scala.collection.immutable.List[scala.collection.mutable.MutableList[String]]
required: java.util.List[java.util.List[String]]
要么
Error:(124, 143) type mismatch;
found: scala.collection.immutable.List[scala.collection.mutable.MutableList[String]]
required: scala.collection.immutable.List[java.util.List[String]]
除非您明确转换内部列表,否则不会对其进行转换。
import scala.collection.JavaConverters._
import java.util.{List=>JavaList}
import scala.collection.immutable.{List => ScalaList}
import scala.collection.mutable.{MutableList => ScalaMutableList}
val a : ScalaList[ScalaMutableList[String]] = List(MutableList())
val b: ScalaList[JavaList[String]]= a.map(_.asJava)
val c: JavaList[JavaList[String]] = b.asJava
我明确了最后一次转换(c = b.asJava
),并建议保留该转换,以使代码更容易为将来的读者使用。
Java对scala的存在一无所知。 因此,整个scala <-> java互操作性应该在scala方面完成。
这个java代码:
import java.util.List;
public class JavaMethod {
public static void main(String[] args){
List<Integer> listInteger = null;
List<Integer> resultListInteger = ScalaMethod.argListInteger(listInteger);
List<List<Integer>> listListInteger = null;
List<List<Integer>> resultListListInteger = ScalaMethod.argListListInteger(listListInteger);
}
}
使用以下scala代码可以很好地编译:
import scala.collection.JavaConverters._
object ScalaMethod {
def argListInteger(listInteger: java.util.List[Integer]): java.util.List[Integer] = {
val scalaList = listInteger.asScala
//Do whatever you want
scalaList
.filter(e => true)
.map(e => e)
//And convert back to Java
.asJava
}
def argListListInteger(listListInteger: java.util.List[java.util.List[Integer]]) = {
val scalaListListInteger = listListInteger.asScala.map(_.asScala)
//Do whatever you want
scalaListListInteger
.filter(e => true)
.map(e => e)
//And convert back to Java
.map(_.asJava)
.asJava
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.