Motivation: A collection has an internal structure (array, tree, graph, etc.), and clients need to traverse its elements without knowing or depending on that structure.
Intent: Provide a way to access the elements of a collection sequentially without exposing its underlying representation.
class WordCollection(private val words: List<String>) : Iterable<String> {
override fun iterator() = object : Iterator<String> {
private var index = 0
override fun hasNext() = index < words.size
override fun next() = words[index++]
}
}
// Usage---works with any Iterable
for (word in WordCollection(listOf("hello", "world"))) {
println(word)
}