Scala for Comprehension

To iterate across the collections in programming languages, we utilize the loops like the for-loop and while-loop. A unique type of loop called a for-comprehension is introduced by the Scala programming language. The construct, like many others in Scala, is a direct descendant of Haskell. It may be used for much more than just looping through collections. When utilizing a functional way of programming, it helps us deal with the syntax’s complexity. 

What is Comprehension in Scala in Ubuntu 20.04

The format for (enumerators) gives “e” in comprehensions where the enumerators is a list of enumerators that is separated by semicolons. A generator that adds new variables is an enumerator, while a filter is an enumerator. Every binding created by the enumerators is evaluated by a comprehension, which then outputs a sequence of values for each value.

Syntax of For-Comprehension in Scala
We are directed by these definitions to the concepts of definitions, filters, and generators for comprehension. A Scala for-comprehension includes the following three expressions:

for {
    e <- elements             // generator
    n =               // definition
    if (expression)   // filter
} yield

Generators are like iterators that iterate over all the elements. Here are two other facts concerning generators: (1) a generator is the first step in every comprehension, (2) multiple generators are used for comprehension.

Filters take the form of Boolean conditions inside of a for-comprehension. A filter serves as a guard, preventing all the values from being used that violate the Boolean condition. Every variable that is accessible inside the scope of the for-comprehension can be used to build a custom Boolean condition inside a filter.

The definition is something that we use to explain precisely what it is that we desire to accomplish or do. For example, we can include all of the operations that we wish to carry out in the defining part.

Example 1: Using For-Comprehension With Yields

To build a new collection out of an existing collection, combine the for loop, your algorithm, and a yield statement. A for-comprehension is the application of a for loop with a yield statement. Put the work in a block following the yield keyword if your approach necessitates numerous lines of code:

We created the object as “Demo1” where we have a definition of the main function. Inside that, we constructed the case class “Subject”. The class has two attributes: the “name” set to string type and the “article” assigned to the “int” type.  After this, we declared a variable “SubjectBase” which has the list representation. The list is initialized with the name of the three subjects and article numbers, respectively.

Next, we defined the generator, definition, and filter inside the for-comprehension which is set in the variable “MoreThanTen”. Within the for-comprehension, the “Subject” cycled over each element inside the “SubjectBase”. Then, we have an “if” statement that indicates the filter here. The “if” statement that has the “Subject.article>=10 && subject.article< 20 ” condition means that the article that doesn’t seem to be between 10 and 20 is filtered away.

Below the for-comprehension, we utilized the “yield” keyword that adds the Since the is a String, the yield operator gathers the result as a List[String].

In the output, you can visualize the list of subject names generated as greater than the article number 10 and less than the article number 20.

Example 2: Using For-Comprehension Without Yields in Scala

We can leave out the yield in comprehension. When that happens, the comprehension gives back a unit. If we want to perform the side effects, this can be useful. Here is a similar program that does not use yield:

We started the program object as “Demo2”. In that, we have the main method definition. Within the main method, we have another function definition. The function is defined as “Verify” which takes the variable “x” as an input and sets it with the type of int. We assigned the for-comprehension to this function. The for-comprehension has the generator and the filter. The generator has the iteration by i and j.

Then, the “i*j >= x” condition is carried out here if the condition is guarded as a filter. As we allotted the value of variable “x” as “5”. In the initial iteration, i and j are both zero. Therefore, i * j is not greater than x, and nothing is thus yielded. Before i is raised to 1, j is increased by three more times. Both values of i and j on each iteration until the condition is satisfied and are printed by the println method.

The Scala compiler upon compilation produces the following results:

Example 3: Using For-Comprehension with Two Generators in Scala

Here is another instance where we employ two generators in the “for-comprehension” but with the yield keyword.

In this example, we have a function definition “Product” that is developed to compute all pairs of numbers ranging between 0 and x-1 whose product matches a specified value y. We have two generators, i and j, which increase by 1 until x as indicated in the for-comprehension. We then use the filter as necessary. We iterate through the list with the for each loop and destructure each member as (i,j). Then, output the pairings.

We also created the list that the method returned without any filters to show the stages that the generators i and j take. The results demonstrate that while one of the generators increases by n-1, the other stays fixed. The second generator increases by 1 when the first one reaches n-1.

You can see the output of the list generated with and without the filter in the for-comprehension as follows:


The different capabilities and functionality of Scala comprehensions were thus made aware to us via the aforementioned article. With the aid of multiple examples, we demonstrated the various advantages of using Scala comprehension in the Scala programming model. After that, we learned about the many capabilities and how yield operates. As a result, we will now be able to create the code while also using the Scala comprehension.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.