How can I use a Java List with Scala's foreach?

nfc-uk picture nfc-uk · Jul 4, 2013 · Viewed 14.2k times · Source

I have tried to convert a java list to a Scala list without success using asInstanceOf, as my returned list from an android call is a java list.

val apList = (wfm.getScanResults:java.util.List[ScanResult])

Wish to do this so that I can use the (new Scala) list in a for comprehension as it doesn't seem to like using a java list in this construct giving me an error.

value foreach is not a member of java.util.List[android.net.wifi.ScanResult]
    for (ap<-apList) { .... }
         ^

Is their a way to use a Java list in a for/foreach, without coercing it? And if I have to coerce, how? as asInstanceOf invokes a r/t error when used in this way.

Answer

om-nom-nom picture om-nom-nom · Jul 4, 2013

There is a set of conversions under scala.collection.JavaConversions and scala.collection.JavaConverters packages. First one acts implicitly on collection, the last one intends to be used explicitly (you take java collection and turn it to the scala analog with .asScala method and vice versa with .asJava).

import scala.collection.JavaConversions._

scala> val xs = new java.util.ArrayList[Int]()
// xs: java.util.ArrayList[Int] = []
xs.add(1)
xs.add(2)
// java.util.ArrayList[Int] = [1, 2]

scala> for(x <- xs) println(x)
1
2

And by the way, the reason asInstanceOf doesn't work is because scala and java collections have entirely different hierarchy and class cast cannot be made. Scala list has no other similarities with Java list except one common predecessor: Object class, so it is no different from trying to cast List to, say, java.util.Random.