4

Can You share any good solution for creating immutable collection in Scala based on full iteration of items in several arrays/another collections?

E.g. in Java you can use:

List<String> signals = ...;
List<SignalState> states = ...;

List<SignalAndState> result = new ArrayList<~>(signals.size() * states.size());

for (String signal: signals) {
  for (SignalState state: states) {
    // some if() condition or process() function can be here 
    result.add(new SignalAndState(signal, state))
  }
}

What are the best practices of building smth like this using Scala? The same approach (using for() in for()) is bad idea, I think, and is not compatible with object-functional nature of Scala language at all.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
izhamoidsin
  • 133
  • 1
  • 1
  • 4
  • 1
    What you compute is basically the Cartesian product of two sequences. See http://stackoverflow.com/questions/8217764/cartesian-product-of-two-lists or http://anders.janmyr.com/2009/10/lists-in-scala.html – Malte Schwerhoff Nov 09 '12 at 12:45

1 Answers1

5

I am not sure about the best practice, but one way you could accomplish this is to us a use a for comprehension to create the collection you are looking for:

val signals = List[String](...)
val states = List[SignalState](...)

for(signal <- signals; state <- states) yield new SignalAndState(signal, state)

That should yield a List[SignalAndState] with all the elements

Alternately, you could use a flatMap and map to accomplish the same result, like:

signals flatMap ( signal => states map ( state => new SignalAndState(signal, state)))
jcern
  • 7,798
  • 4
  • 39
  • 47
  • by the way, the code above (the one with for comprehension) will be internally translated by the compiler into second one with flatMap/map – om-nom-nom Nov 09 '12 at 13:01
  • Why using a List in Scala since List in Scala and Java are totally different? List in Scala is implemented as a LinkedList – Dimitri Nov 09 '12 at 13:21