Specifically I’m looking at Problem 1 here
http://pavelfatin.com/scala-for-project-euler/
The code as listed is as follows
val r = (1 until 1000).view.filter(n => n % 3 == 0 || n % 5 == 0).sum
I can follow everything except for “view”. In fact if I take out view the code still compiles and produces exactly the same answer.
View produces a lazy collection, so that calls to e.g.
filterdo not evaluate every element of the collection. Elements are only evaluated once they are explicitly accessed. Nowsumdoes access all elements, but withviewthe call tofilterdoesn’t create a full Vector. (See comment by Steve)A good example of the use of view would be:
Here Scala tries to create a collection with
1000000000elements to then access the first 10. But with view: