java.util.Iterator to Scala list?

前端 未结 5 1654
走了就别回头了
走了就别回头了 2021-02-12 13:16

I have the following code:

private lazy val keys: List[String] = obj.getKeys().asScala.toList

obj.getKeys returns a java.uti

5条回答
  •  春和景丽
    2021-02-12 14:18

    You don't need to call asScala, it is an implicit conversion:

    import scala.collection.JavaConversions._
    
    val javaList = new java.util.LinkedList[String]() // as an example
    
    val scalaList = javaList.iterator.toList
    

    If you really don't have the type parameter of the iterator, just cast it to the correct type:

    javaList.iterator.asInstanceOf[java.util.Iterator[String]].toList
    

    EDIT: Some people prefer not to use the implicit conversions in JavaConversions, but use the asScala/asJava decorators in JavaConverters to make the conversions more explicit.

提交回复
热议问题