0

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.

Peter Neyens
  • 9,770
  • 27
  • 33
sol
  • 225
  • 4
  • 17
  • 2
    I think you need add more context, such as what is the `JList`, and what does the `indexCols` mean? – Windor C Oct 24 '15 at 02:44
  • 1
    It's usually a good idea to post everything needed to compile your code. This is especially true if we need to `import` something. – jwvh Oct 24 '15 at 05:18

2 Answers2

3

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.

Jason Scott Lenderman
  • 1,908
  • 11
  • 14
0

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 
}
Community
  • 1
  • 1
Onilton Maciel
  • 3,559
  • 1
  • 25
  • 29