java.util.Iterator to Scala list?

前端 未结 5 1646
走了就别回头了
走了就别回头了 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 13:59

    I dislike the other answers. Hell, I dislike anything that suggests using asInstanceOf unless there's no alternative. In this case, there is. If you do this:

    private lazy val keys : List[String] = obj.getKeys().asScala.collect { 
        case s: String => s 
    }.toList
    

    You turn the Iterator[_] into a Iterator[String] safely and efficiently.

提交回复
热议问题