Search code examples
scalaiteratortraversable

Is Traversable a trait or a class


Question 1 -

In the Scala documentation, I found that Traversable is a trait with an abstract method foreach:

http://www.scala-lang.org/docu/files/collections-api/collections.html

Then, why could I instantiate an object of type Traversable?

val t = Traversable(1,2,3)

t.foreach(println _) //where is Scala picking foreach a definition from? 

Question 2 - how is Traversable different from other classes like List or Array? Does it come under Seq, Set or Map category ( I thought other collection inherit from Traversable)

Question 3 - I could do exactly the same for the Iterable trait even though as per documentation, Iterable has an abstract method, iterator:

val v1 = Iterator(1,2,3)

v1.foreach( println _)

What am I missing?


Solution

  • Question 1: When you do Traversable(1,2,3), you are actually calling the apply-method on the companion object of the Traversable trait. This method actually creates a List with the elements you provided (List extends Traversable). The foreach method you are calling is therefore actually the foreach method of List.

    Question 2: Yes, Traversable is the trait at the top of the collections hierarchy in Scala. List and Array are actual examples of some concrete collections, while Traversable is a general trait that a lot of collections implement.

    Question 3: Iterable and Iterator is not the same thing. You seem to mix them up in the question. Iterable(1,2,3) does the exact same thing as Traversable(1,2,3). It calls the apply method on the companion object of Iterable and gives you a List. Iterator(1,2,3) however, calls the apply method on Iterator, and gives you a new Iterator that iterates through the 3 numbers.