1

I am starting in Scala and I want to get an index while I am iterating over a list using the map function.

For example, I have this line of code:

val x= list.flatMap(l => anotherFunction(l.param1.param2List.size * l.multiplier, l, l.param1.param2List(0)))

And I wanted to do something like this:

val x= list.flatMap(l => anotherFunction(l.param1.param2List.size * l.multiplier, l, l.param1.param2List(index)))

Is there any way to add a counter or something like that in order to get the index as if I was looping through the list in a for cycle? Is it possible or should I try another approach?

J Costa
  • 23
  • 1
  • 3
  • 7
    Possible duplicate of [How can I use map and receive an index as well in Scala?](https://stackoverflow.com/questions/2213323/how-can-i-use-map-and-receive-an-index-as-well-in-scala) – Tzach Zohar May 23 '17 at 19:47
  • it is a duplicate: i.e https://stackoverflow.com/questions/20363754/accessing-an-index-in-a-list-in-scala – Pavel May 23 '17 at 19:51

1 Answers1

1

I am sure this is a duplicate, use something like:

val l = List(1, 2, 4)
val r = l.zipWithIndex

Please read api documentation on collections:

http://www.scala-lang.org/api/current/scala/collection/immutable/List.html

What exactly are you trying to achieve ?

Pavel
  • 1,519
  • 21
  • 29