How do you return an Iterator in Scala?

Geo picture Geo · Jan 25, 2010 · Viewed 16k times · Source

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?

Answer

Mitch Blevins picture Mitch Blevins · Jan 25, 2010

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
  }