44

I'd like the convienience of

for i, line in enumerate(open(sys.argv[1])):
  print i, line

when doing the following in Scala

for (line <- Source.fromFile(args(0)).getLines()) {
  println(line)
}
Ben James
  • 121,135
  • 26
  • 193
  • 155
Abhinav Sharma
  • 1,145
  • 4
  • 11
  • 12

2 Answers2

56

You can use the zipWithIndex from Iterable trait:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
   println(i, line)
}
Ben James
  • 121,135
  • 26
  • 193
  • 155
rafalotufo
  • 3,862
  • 4
  • 25
  • 28
10

As already answered by others, if you want your index to start from 0, you can use zipWithIndex:

for ((elem, i) <- collection.zipWithIndex) {
    println(i, elem)
}

Because zipWithIndex creates a copy of the collection if called on the collection itself, you may want to call it to a view of the colleciton instead: collection.view.zipWithIndex.

Nonetheless, Python's enumerate has an optional parameter to set the start value of your index. In scala, you can do:

for ((elem, i) <- collection.zip(Stream from 1) {
    println(i, elem)
}

For a longer discussion, read https://alvinalexander.com/scala/how-to-use-zipwithindex-create-for-loop-counters-scala-cookbook.

janluke
  • 1,567
  • 1
  • 15
  • 19