Scala Foundation Course - For Comprehension


Welcome back. We were discussing Scala control structures. The last item among the control abstraction is the for expression. The Scala's for loop is a swiss army knife of iterations. Here is the general structure of the for expression.

It looks simple, but I realized that it is quite confusing to explain the above structure. Let me take a progressive approach to explain that. To simplify the structure, let's ignore the yield for now. The yield is optional. You will be using it most of the time, but let's keep it aside for the moment.
Now the structure looks like this.

Let's try to understand this structure.If you learned other languages, the above structure should look familiar. The things inside the parenthesis will control the number of iterations, and those curly braces represent the body of the loop. That's how it is in most of the languages.

You can have one or more expressions within the body. If you have a single expression, curly braces are optional. We don't have any complexity for the body of the loop. It is almost same as any other language.
But the seq is somewhat complicated. It keeps confusing a lot of people.

The sequence generator in Scala for loop

Let’s start with the simplest form of the seq and then expand it step by step. The simplest form of seq is a generator that looks something like below.

The col is a Scala collection, and e is a value that binds to each element of the collection. Let's take an example.


So far so good. But one thing to notice here is the presence of a collection. You will need a collection to iterate using a Scala for loop. A beginner takes a lot of time to realize the fact that you need a collection to use Scala for expression. If you don't have a collection, you can't use a Scala for loop. We wrote 1 to 5 in the above example. That gives you a feeling that you are iterating five times, but in fact, you are iterating over a range collection. The range collection is implicit. The body of the for loop in this example is quite simple. Just a println. Let's add some more code to it.

The above code is an example of the most basic form of the for loop. Iterate over a collection and do something with each element of the collection. Now, It is time for a quiz and here is my question. Given the below list, can you generate the same output as above without using a for loop?

All you need to do is to print the capital of the country in the list. You already know it. I explained that in an earlier video.

Does the above code look familiar? We learned it already in an earlier video. The foreach method is a higher order control abstraction. The sole purpose of the foreach method is to iterate over each element of the collection and apply the given code. We are doing the same thing as we did in the for loop. Both the constructs are the same. Now I have another question. Why do we have two constructs for the same thing?

Redefine the Scala for loop

The Scala for loop is just a syntactic sugar for Higher Order Control Abstractions. Internally, both are same. What does it mean?
That means the Scala compiler will convert the for loop to a combination of following control abstractions.

  1. foreach
  2. map
  3. flatMap
  4. withFilter

In other words, Scala doesn't have a for loop. It's just a syntactic sugar for a set of these methods. So, if you don't like the for loop, you can manage to code in Scala without even worrying about the for loops. The real purpose of the Scala for expression is to write the code in a way that makes more sense. You should use the for expression when you think your code is getting too cryptic using these methods and it would make more sense if you implement it using a for expression. Once you know that the for expression is just a syntactic sugar, it becomes quite easy to understand the for expression.

The Yield in Scala for expression

Now let's bring the yield back into the structure.

In the absence of yield, the for loop behaves like a foreach method. When we apply the yield, it behaves like a map method. I hope you still remember the difference between foreach and the map method. The foreach returns a Unit whereas the map method returns a new collection. So, can you update the above example to behave like a map method? I mean, instead of printing the capitals of the countries, return a new collection.
To achieve that, we need to make two changes.

  1. Place the yield just before the body of the loop.
  2. Remove those println and return the string.

Simple. Isn't it. The for loop becomes a for expression. Because, now it returns a value. You can also assign the result of the above for expression to a value.


Nested for loop

Now we need to get into the further expansion of the seq.

I said that the simplest form of seq is a generator that looks something like below.

Scala allows you to have multiple generators. But the next generator will cause a nested loop. Let's see a simple example.

So, for each value of i, you are getting two values of j. That's what the nested loop is. You can extend the nesting further.

If the code between the pair of parenthesis is getting complex, you can use curly braces.

Now the semicolon is optional. you can remove that.


The Guards in Scala for loop

For each generator, you can apply filters. Let me show you.

The above example applies a filter on the on the generator for the j. I am putting a filter to eliminate odd numbers. Only those elements of j will pass through that qualify the filter condition. You can also write one expression on each line.

Assignments in Scala for loop

Let's take a better example to understand the power and flexibility of the Scala for loop. I have one file with the content shown below.
Save the content as employees.csv

The data in the file contains the list of employees. Let's create a for loop to print all the records.

Simple. Isn't it. But I am not interested in all those fields. I just want to see id, first name, last name, and the department id. Can we print only these fields. Let's do it.

So, we split the line over a comma. Take only four fields. We did that in the body of the for loop. The for loop also allows you to embed assignment as part of the generator. Same as we embed a filter for the generator. So, the code should look like this.

So, the idea is to expand the for comprehension instead of expanding the body of the for loop. Keep the body as simple as possible.
Let me ask you a question. I am only interested in department number 60. Can you filter out others?
Here is the code.

So, it is not necessary to apply a filter before you apply an assignment. You have all the freedom. The above example looks like an SQL query.

Can you extend the above example further? Instead of showing the department Id, can we get the department name? Basically, I want to see all the employees with their department Id replaced with their department names. You have a separate file for departments.
Save the below content as departments.csv

Does the requirement look like another SQL query? Join two files and get the department name. Here is the Scala code.

We used a Scala nested loop. This example may not be the best way to solve that problem. But I just wanted to show you the power and flexibility of the Scala for expression.

Summary

We started the discussion with below structure.

Now, you know that the seq may have three components.

  1. A Generator
  2. A Filter or Guard
  3. A Definition

You need a generator to create a for loop in Scala. That generator is a Scala collection. Without a generator, you can’t create a Scala loop.
The filter and the definition are optional. You can have it if you need it.
If you want a nested loop, you can repeat the entire set for next level of iteration.
You can use the yield if you want to return the output as another collection. The yield is also optional. In the absence of yield, Scala for loop behaves like a foreach method on a collection.
Scala for loop is just a syntactic sugar. You can model any for expression using a combination of following collection methods. That’s what the Scala compiler internally does.

  1. foreach
  2. map
  3. flatMap
  4. withFilter

Thank you for watching Learning Journal.
Keep Learning and Keep Growing.


You will also like: