Melbourne Meeting – February 2015

Monday 16th February

Iterators – Presented by John McDonald

Iterators are a standard design pattern that return a sequence of values. Iterators have one public method – MoveNext, to move to the next value in the sequence and one public property – Current, which returns the current value.
In Delphi, Iterators are generally called Enumerators. Enumerable types are types that can create an Enumerator, usually with a GetEnumerator method.
John demonstrated how Iterators can be used in Delphi, and how the for-in construct can significantly reduce the code required. Most of the collection types in the RTL are enumerable types, and the for-in construct can be used with all these collections. For-in statements can also be used with elements in an array or set, and the characters in a string.
John showed several examples of how to code an Enumerator, including a class that generated members of the Fibonacci sequence, another that returned objects loaded from the records in a file and one that returns the filenames in a directory tree. Some of the examples were generic classes.
He also showed how to return enumerable types from a function without creating a memory leak. In this example, the function was passed an enumerable and a filter function, and returned a filtered enumerable which was used by the for-in loop.
The final example was a generic enumerable class which created enumerators formed by merging two supplied enumerable classes.
Presentation Code ZIP


Posted in Meetings, Melbourne Tagged with: