score:55

Accepted answer

You can use the zipWithIndex from Iterable trait:

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

score: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.


Related Query

More Query from same tag