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) }
}		

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group