Control Structures in Scala
In the following lesson, you will be introduced to control structures.
We'll cover the following
Introduction
Control structures can be thought of as blocks of code which determine or dictate the flow in which statements (lines of code) are executed; they basically control the flow of code. For instance, a block of code can flow in a sequential manner and there is a control structure which ensures its statements are executed sequentially. A block of code can also flow in an iterative manner and there are control structures which ensure its statements are executed iteratively.
Before we dive into Scala’s control structures, it’s important to first visit the programming paradigms; imperative and declarative.
Imperative vs. Declarative
Control structures follow an imperative programming paradigm. While Scala, as discussed in the first chapter, is a functional programming paradigm language, which is a subset of the declarative programming paradigm. But what does it mean for a language to be declarative or imperative?
In one sentence…imperative programming is how to execute a sequence of code and declarative programming is what a sequence of code should do.
Let’s take a real-life example. Imagine you’ve invited a friend to your house. The goal is for your friend to reach your house from their house. You can either give step-by-step directions to your house from your friend’s house or you can give your friend an address and tell them to come to the location of the address.
The first approach is imperative as you are telling your friend how to reach the goal. While the second approach is declarative as you are telling your friend what to do.
Scala’s Approach
Scala doesn’t have an extensive list of control structures with only six control structures in total. The reason for this is that Scala allows control abstraction; the ability to create your own control structures. While control abstraction is out of the scope of this course, it is important to mention here as it is a feature unique to Scala.
Scala’s control structures are if
, while
, for
, try
, match
, and function calls.
In Scala, control structures return values just like functions. With this, Scala brings a functional approach to an imperative paradigm. The ability of a control structure to return a value reduces the need to create temporary variables for holding results resulting in cleaner and more concise code.
In the next lesson, we will cover the first control structure: if
.