Scala Foundation Course - Higher Order Control Abstractions


Welcome back. In the earlier videos, I talked about Scala control abstraction. But do you understand the term abstraction? What does it mean?
Abstract means hide something. Right?
Why do we hide something?
The purpose is to achieve simplicity and bring more clarity. Sometimes, things are easy to understand when we hide the complex and unnecessary internal details. In computer science, we talk about two different types of abstractions.

  1. Data abstraction
  2. Control abstraction

The data abstraction is to hide the implementation of complex data types or data structures.
The control abstraction is to hide the implementation of complex execution flow and some low-level activities.
Let me give you an example of control abstraction in Scala.
Assume, you are working to implement a library to work with data files. You realize that there is a common pattern of activities. You outlined it like this.


  1. Open the File.
  2. Read it line by line.
  3. Perform some operations on each line.
  4. Make sure the file is closed at the end.

A typical Java programmer will write a lot of code with try-catch blocks. Can you create a control abstraction for this?
In fact, you want to create a function that allows other programmers to implement the given pattern using following code.

What do you think? Just a single line. Everything else is abstracted away. The withTextFile is a function that takes two arguments. The first argument is the file location and the second argumentis a function literal. The function opens the given file, it reads the file line by line, and apply the function literal for each line.
In fact, this function is a specialized loop construct. You compare it with the repeat until example.

Do they look similar? That's the point I wanted to make.
Scala gives you an ability to create new control abstractions of your own. This capability allows you to abstract away the code clutter and make your final code precise, neat and easy to understand. And that's what we call Higher Order Control abstraction in Scala.
If you are using any of the Spark libraries, you will be noticing such abstractions more than often. If you are implementing a library in Scala, you will be implementing many of such abstractions. The Scala language library takes the same approach and implements the most necessary control abstraction for almost every collection type in Scala.
In the next video, we will investigate some of the most critical control abstraction for Scala collections.


You will also like: