Search code examples
scalaenumerate

Is there a Scala equivalent for the python enumerate?


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

Solution

  • You can use the zipWithIndex from Iterable trait:

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