Is there a Scala equivalent for the python enumerate?

Abhinav Sharma picture Abhinav Sharma · Jun 26, 2011 · Viewed 10k times · Source

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)
}

Answer

rafalotufo picture rafalotufo · Jun 26, 2011

You can use the zipWithIndex from Iterable trait:

for ((line, i) <- Source.fromFile(args(0)).getLines().zipWithIndex) {
   println(i, line)
}