Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

scala - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...