java.util.Iterator to Scala list?

rshepherd picture rshepherd · Sep 28, 2011 · Viewed 21k times · Source

I have the following code:

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

obj.getKeys returns a java.util.Iterator<java.lang.String>

Calling asScala, via JavaConverers (which is imported) according to the docs..

java.util.Iterator <==> scala.collection.Iterator 

scala.collection.Iterator defines

def toList: List[A] 

So based on this I believed this should work, however here is the compilation error:

[scalac]  <file>.scala:11: error: type mismatch;
[scalac]  found   : List[?0] where type ?0
[scalac]  required: List[String]
[scalac]  private lazy val keys : List[String] = obj.getKeys().asScala.toList
[scalac]  one error found

I understand the type parameter or the java Iterator is a Java String, and that I am trying to create a list of Scala strings, but (perhaps naively) thought that there would be an implicit conversion.

Answer

Matthew Farwell picture Matthew Farwell · Sep 28, 2011

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.