In Scala, what does "view" do?

View produces a lazy collection, so that calls to e.g. filter do not evaluate every element of the collection. Elements are only evaluated once they are explicitly accessed. Now sum does access all elements, but with view the call to filter doesn't create a full Vector. (See comment by Steve)

A good example of the use of view would be:

scala> (1 to 1000000000).filter(_ % 2 == 0).take(10).toList
java.lang.OutOfMemoryError: GC overhead limit exceeded

Here Scala tries to create a collection with 1000000000 elements to then access the first 10. But with view:

scala> (1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
res2: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

I don't know much about Scala, but perhaps this page might help...

There are two principal ways to implement transformers. One is strict, that is a new collection with all its elements is constructed as a result of the transformer. The other is non-strict or lazy, that is one constructs only a proxy for the result collection, and its elements get constructed only as one demands them.

A view is a special kind of collection that represents some base collection, but implements all transformers lazily.

So it sounds as if the code will still work without view, but might in theory be doing some extra work constructing all the elements of your collection in strict rather than lazy fashion.

Tags:

Scala