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.
That would work if obj.getKeys() was a
java.util.Iterator<String>. I suppose it is not.If
obj.getKeys()is justjava.util.Iteratorin raw form, notjava.util.Iterator<String>, not evenjava.util.Iterator<?>, this is something scala tend to dislikes, but anyway, there is no way scala will type your expression asList[String]if it has no guaranteeobj.getKeys()contains String.If you know your iterator is on Strings, but the type does not say so, you may cast :
(then go on with
.asScala.toList)Note that, just as in java and because of type erasure, that cast will not be checked (you will get a warning). If you want to check immediately that you have Strings, you may rather do
which will check the type of each element while you iterate to build the list