簡體   English   中英

如何將scala.collection.immutable.List [scala.collection.mutable.MutableList [String]]轉換為java.util.List [java.util.List [String]]

[英]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.MutableListutil.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM