Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return an Iterator in Scala?

Tags:

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?

like image 960
Geo Avatar asked Jan 25 '10 20:01

Geo


People also ask

Can you return an iterator?

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.

What is a iterator return type?

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.

What is iterable in Scala?

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.


1 Answers

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   } 
like image 185
Mitch Blevins Avatar answered Nov 04 '22 17:11

Mitch Blevins