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

前端 未结 4 1671
死守一世寂寞
死守一世寂寞 2020-12-07 22:09

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

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

4条回答
  •  一个人的身影
    2020-12-07 22:49

    See Views from Scala 2.8 Collections API.

    Scala collections are by default strict in all their transformers, except for Stream, which implements all its transformer methods lazily. However, there is a systematic way to turn every collection into a lazy one and vice versa, which is based on collection views. A view is a special kind of collection that represents some base collection, but implements all transformers lazily.

    ...

    There are two reasons why you might want to consider using views. The first is performance. You have seen that by switching a collection to a view the construction of intermediate results can be avoided. These savings can be quite important.

    ...

    The second use case applies to views over mutable sequences. Many transformer functions on such views provide a window into the original sequence that can then be used to update selectively some elements of that sequence.

提交回复
热议问题