Example class diagram

Using the iterator design pattern, we can create our own objects that act as collections and we can use them in loops. In Java, there is an interface called Iterator, which we can implement for this purpose. In Scala, we can mix in the Iterator trait and implement its hasNext and next methods.

For the class diagram and the example, let's have a ClassRoom class that will support a foreach loop running through all students. The following diagram shows our class diagram:

We've decided on our ClassRoom class to implement Iterable, which should return an Iterator and then return a new instance of our iterator when the method ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.