This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.11, “How to Use zipWithIndex or zip to Create Loop Counters”
Problem
You want to loop over a sequential collection, and you’d like to have access to a counter in the loop, without having to manually create a counter.
Solution
Use the zipWithIndex
or zip
methods to create a counter automatically. Assuming you have a sequential collection of days: