...

/

Iterator design pattern

Iterator design pattern

Learn how the Iterator pattern is implemented in Kotlin, and how it helps us with complex data structures.

Introduction to the Iterator design pattern

The Iterator pattern is the companion to the Composite design pattern. They’re very different but complement each other well.

As we discussed before, a squad consists of troopers or other squads. Let’s create one now:

val platoon = Squad(
Trooper(),
Squad(
Trooper(),
),
Trooper(),
Squad(
Trooper(),
Trooper(),
),
Trooper()
)
Creating a platoon of soldiers using the Squad and Trooper classes.

Here, we created a platoon that consists of four troopers in total. It would be useful if we could print all the troopers in this platoon using a for loop. Let’s just try to write that code and see what happens:

for (trooper in platoon) {
println(trooper)
}
Printing troopers in platoon
...