We also use for loops to iterate over sequences like strings and arrays. We can run into problems when we manipulate a sequence while iterating on it.
For example, if we append elements to an array while iterating on it:
val fruits = scala.collection.mutable.ArrayBuffer("banana", "orange")
for (fruit <- fruits) {
fruits += "kivi"
}
Every time we enter this loop, we add a kivi item to the end of the list that we are iterating through, so we would never make it to the end of the list: it would keep growing forever.
Scala stops this for us: after the first item is added, the loop's next step throws a ConcurrentModificationException ("mutation occurred during iteration").
Changing a collection while looping over it is always a bug. And when nothing stops the loop, the collection keeps growing forever: an infinite loop. As programmers, we want to make sure we never write infinite loops, as they make our program run forever and completely unusable.
Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.