Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are views for collections and when would you want to use them?

In Scala, for many (all?) types of collections you can create views.

What exactly is a view and for which purposes are views useful?

like image 760
Jesper Avatar asked Jul 29 '10 10:07

Jesper


People also ask

What is view collections?

A collection view manages an ordered set of content, such as the grid of photos in the Photos app, and presents it visually.

What is a view in Scala?

The View is a special kind of collection in Scala that takes a base collection and executes transformer methods on that collection lazily. We can turn every Scala collection into a lazy representation and back via the view method.

What is collect Scala?

Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Collections may be strict or lazy.


2 Answers

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:

val xs = List.tabulate(5)(_ + 1) val ys = xs.view map { x => println(x); x * x } 

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 in 1 being printed. If you want to get a strict version of the collection again you can call force 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.

like image 103
Moritz Avatar answered Sep 30 '22 23:09

Moritz


One use case is when you need to collect first result of elements transformation:

    case class Transform(n: Int) { println("Transform "+n)}     val list = List(1,2,3,4,5)     list.view.map(v => Transform(v)).collectFirst{case Transform(3) => println("found")} 

Prints:

Transform 1 Transform 2 Transform 3 found 

While:

    list.map(v => Transform(v)).collectFirst{case Transform(3) => println("found")} 

Prints:

Transform 1 Transform 2 Transform 3 Transform 4 Transform 5 found 
like image 23
Markus Marvell Avatar answered Oct 01 '22 00:10

Markus Marvell