Iterator design pattern
Explore the Iterator design pattern to manage complex collections in Kotlin. Learn how to implement the iterator() function with generics, enabling iteration over nested squads and troopers seamlessly. Gain practical insight into flattening data structures for use with Kotlin's for loop, improving code simplicity and reusability.
We'll cover the following...
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())
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)}
Although this code doesn’t compile, the Kotlin compiler provides us with a useful hint:
>For loop range must have an iterator method
Before we follow the compiler’s ...