Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 883
nfc-uk Avatar asked Jul 03 '13 23:07

nfc-uk


1 Answers

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.

like image 74
om-nom-nom Avatar answered Nov 20 '22 13:11

om-nom-nom