In Scala, for many (all?) types of collections you can create views.
What exactly is a view and for which purposes are views useful?
In Scala, for many (all?) types of collections you can create views.
What exactly is a view and for which purposes are views useful?
view is used for lazy computation,but not for saving memory.
When you create a view against a collection, the memory has already been allocated forthe collection.
When creating the view with
val view = Range(1,9).view.
, the collection has already been allocated the memory, if it is too large,say,Range(1,1000000000)
, OOM can't be avoidOne use case is when you need to collect first result of elements transformation:
Prints:
While:
Prints:
Views are non-strict versions of collections. This means that the elements are calculated at access and not eagerly as in normal collections.
As an example take the following code:
Just this will not print anything but every access to the list will perform the calculation and print the value, i.e. every call to
ys.head
will result in1
being printed. If you want to get a strict version of the collection again you can callforce
on it. In this case you will see all numbers printed out.One use for views is when you need to traverse a collection of values which are expensive to compute and you only need one value at a time. Also views let you build lazy sequences by calling
toStream
on them that will also cache the evaluated elements.See Views from Scala 2.8 Collections API.