I have a Scala method being used in java class throwing the error below. For some reason the implicit conversions are not working for List
of Lists
but it does work for a List
. (for ex: mutable.MutableList
to 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]]
or
Error:(124, 143) type mismatch;
found: scala.collection.immutable.List[scala.collection.mutable.MutableList[String]]
required: scala.collection.immutable.List[java.util.List[String]]
The inner list will not be converted unless you explicitely convert it.
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
I made the last conversion (c= b.asJava
) explicit and I would recommend to keep it so to make the code easier to ready for future readers.
Java knows nothing about scala existence. So whole scala<->java interoperability should be done on scala side.
This java code:
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);
}
}
compiles well with this scala code:
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.