Iterator Pattern in Kotlin | Design Patterns

Iterator Pattern is a relatively simple and frequently used design pattern. There are a lot of data structures/collections available in every language. Each collection must provide an iterator that lets it iterate through its objects.

However while doing so it should make sure that it does not expose its implementation.


package behavioral
class Novella(val name: String)
class Novellas(val novellas: MutableList<Novella> = mutableListOf()) : Iterable<Novella> {
    override fun iterator(): Iterator<Novella> = NovellasIterator(novellas)
}
class NovellasIterator(val novellas: MutableList<Novella> = mutableListOf(), var current: Int = 0) : Iterator<Novella> {
    override fun hasNext(): Boolean = novellas.size > current
    override fun next(): Novella {
        val novella = novellas[current]
        current++
        return novella
    }
}
fun main(args: Array<String>) {
    val novellas = Novellas(mutableListOf(Novella("Test1"), Novella("Test2")))
    novellas.forEach { println(it.name) }
}		

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions