theexplorer
theexplorer

Reputation: 359

Scala collection hierarchy

I was looking at a photo that shows the Collections Hierarchy in Scala.

It looks like in the top of the hierarchy there is the Traversable Trait, one step down there is the Iterable Trait which has the iterator() function and going down the road there's List and Array...

Creating a simple List object and trying to invoke iterator() on it threw an error that said it is not a part of List.

Now, I know I can get an Iterable representation of the list and then iterate over it with the Iterator, but my question is more about understanding how this thing works: shouldn't the List class get the iterator() function since Iterator is higher up the same hierarchy?

I'm looking at things in my question in the eyes of a Java developer.

Thank you.

Upvotes: 0

Views: 158

Answers (1)

Giovanni Caporaletti
Giovanni Caporaletti

Reputation: 5556

List[A], as you stated, is an Iterable[A] and as such it has an iterator method (without brackets) that can be called to obtain an iterator over the elements of the list:

val it: Iterator[Int] = List(1, 2, 3).iterator

If you call it with brackets iterator(), it doesn't work because the iterator method is defined without them in the GenIterableLike trait:

trait GenIterableLike[+A, +Repr] extends Any with GenTraversableLike[A, Repr] {
  def iterator: Iterator[A]
...

You can read about method invocation in scala here. Arity-0 methods can be defined with or without brackets, but if you go for the latter (def m = {}), you cannot call them like this: m()

Upvotes: 4

Related Questions