Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
views

What are Scala views?

Sarvech Qadir

By default, most Scala collections are strict in nature but they can be lazy as well. A programmer can systematically convert collections into lazy ones using views. Views are special kinds of collections that may represent some of the base collections e.g List, Set Map, Tuple, but in reality, implements all the methods and transformersMethods such as map, filter or ++ lazily.

One can easily convert any collection to its view using the following syntax:

Syntax

View_list = Collection.view

Using .view will return all transformers lazily implemented.

In order to go back, one can use the following syntax:

View_list.to(List)
View in Scala
View in Scala

Why do we use Views?

One of the most important reasons to use views is the enhanced performance. Since views implement all transformers lazily, there are no intermediate results, which causes immense savings in performance. Views are beneficial especially when modularity and efficiency are key for a program.

It is advised to restrict views to mostly functional code as they can cause delayed evaluations.

Code

Let’s look at a basic use of a view. In the first, we will try to create a huge list without using view. This should return a huge error, because, creating such a long list causes a runtime error.

object Main extends App {
    val v = (1 to 100000000).map(_ + 1).take(5).toList
    println(v)
}

Now, we will do the same but this time, we will use .view method. This works perfectly because the use of view allows creation of a lazy list. The list is only created as it is required and entire list is not initialized like in the code above.

object Main extends App {
    val v = (1 to 100000000).view.map(_ + 1).take(5).toList
    println(v)
}

RELATED TAGS

scala
views

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring