I want to iterate a list of Pair
objects, but have a few problems. As following variable:
val list: JList[Pair[Integer, Integer]]
for (pair <- list){
//how to get first value and second value of pair instance
}
When I use for
with <-
to iterate, I can't get Pair
instance and can't get properties of Pair
.
I'm assuming JList
here is the java swing component. If that is the case, then you cannot so far as I know use it directly in a for-comprehension. Instead you'll need to do something like:
import scala.collection.JavaConversions._
for (pair <- list.getSelectedValuesList) {
//do something with pair
}
The import pulls in implicits that will convert from Java collections to Scala collections. You'll need this because the for-comprehension you're using is de-sugared to a foreach
method call, and java.util.List
does not define a foreach
method.
Incrementing Jason's answer. It is usually recommended to use JavaConverters
instead of JavaConversions
to avoid nasty issues . It is a little bit more verbose, but safer.
The solution would be something like this:
import scala.collection.JavaConverters._
for (pair <- list.asScala.getSelectedValuesList) {
//do something with pair
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.