How to get Scala List from Java List?

前端 未结 6 1341
半阙折子戏
半阙折子戏 2021-01-29 23:23

I have a Java API that returns a List like:

public List getByXPath(String xpathExpr)

I am using the below scala code:

         


        
6条回答
  •  轮回少年
    2021-01-29 23:48

    If you have to convert a Java List to a Scala List[ClassB], then you must do the following:

    1) Add

    import scala.collection.JavaConverters._
    

    2) Use methods asScala, toList and then map

    List  javaList = ...
    var scalaList[ClassB] = javaList.asScala.toList.map(x => new ClassB(x))
    

    3) Add the following to the ClassB constructor that receives ClassA as a parameter:

    case class ClassB () {
       def this (classA: ClassA) {
          this (new ClassB (classA.getAttr1, ..., classA.getAttrN))
       }
    }
    

提交回复
热议问题