How to lazily evaluate collections in Scala

Knoldus

The Scala language provides to ways to implement the collections. One is strict and other is non-strict or lazy.

Whenever, the instance of a collection (except for the Streams) is created, it creates the strict version of the collection which means memory is allocated at the same time.

A simple example of strict collection is:


val list = List(1,2,3,4,5,6,7,8,9,10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

The above code, the memory would be allocated for the List immediately.

But whenever a view in the collection is created, it makes that collection as a lazy collection which means memory allocation would not be done at the time of initialization, instead, it would take place whenever they are actually accessed or some transformations are applied on them.

For example,


val listView = List(1,2,3,4,5,6,7,8,9,10).view
listView: scala.collection.SeqView[Int,List[Int]] = SeqView(...)

Here, the type of listView is SeqView[Int, List[Int]]

View original post 389 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s