1
votes

I have a function that takes a value and returns a list of pairs, pairUp.

and a key set, flightPass.keys

I want to write a for loop that runs pairUp for each value of flightPass.keys, and returns a big list of all these returned values.

val result:List[(Int, Int)] = pairUp(flightPass.keys.toSeq(0)).toList
for (flight<- flightPass.keys.toSeq.drop(1))
{val result:List[(Int, Int)] = result ++ pairUp(flight).toList}

I've tried a few different variations on this, always getting the error:

<console>:23: error: forward reference extends over definition of value result
for (flight<- flightPass.keys.toSeq.drop(1)) {val result:List[(Int, Int)] = result ++ pairUp(flight).toList}
                                                                             ^

I feel like this should work in other languages, so what am I doing wrong here?

2

2 Answers

0
votes

First off, you've defined result as a val, which means it is immutable and can't be modified.

So if you want to apply "pairUp for each value of flightPass.keys", why not map()?

val result = flightPass.keys.map(pairUp)  //add .toList if needed
0
votes

A Scala method which converts a List of values into a List of Lists and then reduces them to a single List is called flatMap which is short for map then flatten. You would use it like this:

flightPass.keys.toSeq.flatMap(k => pairUp(k))

This will take each 'key' from flightPass.keys and pass it to pairUp (the mapping part), then take the resulting Lists from each call to pairUp and 'flatten' them, resulting in a single joined list.