Iterators in Kotlin

Suneet Agrawal
2 min readApr 12, 2022

--

Collections (Sets, Maps and Lists) are something we use daily. Traversing (Iteration) is the most common operation we perform over any collection.
Iterators are used to traverse over a collection object. It provides access to the elements of the collection object sequentially without exposing the underlying structure of the collection.

This post was originally posted at https://agrawalsuneet.github.io/blogs/iterators-in-kotlin/ and reposted on Medium on 12th April 2022.

How to get an iterator object?

An iterator reference object can be obtained using iterator() function which is declared in the Iterable interface for generic type T. The Iterable interface is extended by the Collection interface which is implemented by all immutable Sets, Maps and Lists.

/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over.
* @param T the type of element being iterated over. The iterator is covariant in its element type.
*/
public interface Iterable<out T> {
/**
* Returns an iterator over the elements of this object.
*/
public operator fun iterator(): Iterator<T>
}

The Iterable has one more variant interface as MutableIterable which has the same iterator() function but this interface is extended by MutableCollection which is implemented by mutable Sets, Maps and Lists.

/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over and that supports removing elements during iteration.
* @param T the type of element being iterated over. The mutable iterator is invariant in its element type.
*/
public interface MutableIterable<out T> : Iterable<T> {
/**
* Returns an iterator over the elements of this sequence that supports removing elements during iteration.
*/
override fun iterator(): MutableIterator<T>
}

How to use an iterator object?

Please continue reading at https://agrawalsuneet.github.io/blogs/iterators-in-kotlin/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--