What must I do in order to be able to return an Iterator from a method/class ? How would one add that trait to a class?
Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
Iterator is generic and doesn't return a specific type unless you define it in the ArrayList. Iterator is an interface (part of the Java Collections) that returns the type that was passed to it. The Iterator is used to traverse the list of elements, and remove an element if necessary.
Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements. [...] This trait implements Iterable's foreach method by stepping through all elements using iterator.
You can extend Iterator, which will require that you implement the next
and hasNext
methods:
class MyAnswer extends Iterator[Int] { def hasNext = true def next = 42 }
But, you will get more flexibility if you extend Iterable, which requires you implement elements
(or iterator
in 2.8):
class MyAnswer extends Iterable[Int] { def iterator = new Iterator[Int] { def hasNext = true def next = 42 } }
A common idiom seems to be to expose an iterator to some private collection, like this:
class MyStooges extends Iterable[String] { private val stooges = List("Moe", "Larry", "Curly") def iterator = stooges.iterator }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With