How to use Java list with Scala foreach?

I tried converting a java list to a Scala list without success using asInstanceOf since my returned list from an android call is a java list.

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

Desire to do this so that I can use the (new Scala) list in understanding, since it doesn't seem to him that using a java list in this construct gives me an error.

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

Is their way to use the Java list in for / foreach without forcing it? And if I need to force, how? since asInstanceOf causes an r / t error when used this way.

+7
java scala scala-java-interop
source share
1 answer

There is a set of transformations under scala.collection.JavaConversions and scala.collection.JavaConverters . The first one acts implicitly on collection, the last one is intentionally used explicitly (you take the java collection and pass it to the scala analog using the .asScala method and vice versa .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 does not work, because scala , and java collections have a completely different hierarchy and class. cannot be done. A scala list has no other similarities to a Java list, except for one common predecessor: the Object class, so it is no different from how to use List to, say, java.util.Random.

+17
source share

All Articles