views:

221

answers:

2

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?

+13  A: 

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
  }
Mitch Blevins
+5  A: 

For a method, just yield:

def odd(from: Int, to: Int): List[Int] = 
  for (i <- List.range(from, to) if i % 2 == 1) yield i
Jordão