Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: What is the difference between Traversable and Iterable traits in Scala collections?

I have looked at this question but still don't understand the difference between Iterable and Traversable traits. Can someone explain ?

like image 270
Rahul Avatar asked Sep 15 '11 02:09

Rahul


People also ask

What is traversable in Scala?

Traversable is accomplished by the Scala's Collection classes. It is obligatory for Traversable to define foreach method only, as Traversable can inherit all the other methods. The foreach method could traverse all the elements of the Scala's collection class.

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.


1 Answers

Think of it as the difference between blowing and sucking.

When you have call a Traversables foreach, or its derived methods, it will blow its values into your function one at a time - so it has control over the iteration.

With the Iterator returned by an Iterable though, you suck the values out of it, controlling when to move to the next one yourself.

like image 148
Duncan McGregor Avatar answered Sep 21 '22 00:09

Duncan McGregor