4 Definitions of an Iterator

Yuhuan Jiang
Aug 23, 2017 · 1 min read

Iterators can be defined in at least four ways:

HasNext & Next

This is the most common definition as seen in Java and Scala. hasNext indicates whether the iterator is finished. next fetches advances the iterator and provides the next element in the iterator if possible. Calling next when hasNext is false will result in an exception.

Java/Scala style iterator

Current & MoveNext

This definition is found in C#. Current returns the first element that the iterator is pointing to (undefined before the first call to MoveNext). MoveNext advances the iterator to the next item, and returns true/false depending on whether the new position still has an item.

Option

This is a succinct version of the definition above. Found in the Rust language. The two methods in the definition above are combined into one method which returns an optional value of the item type.

Exceptions

This is very similar to the definition above. The difference is that when there are no more items, instead of returning an None optional value, an exception is thrown. Any iterator should implement the magic method __next__.

)

Yuhuan Jiang

Written by

http://yuhuan.me

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade