Chapter 4. Control Structures
As their name implies, control structures provide a way for programmers to control the flow of a program. They’re a fundamental feature of programming languages that let you handle decision making and looping tasks.
Prior to learning Scala back in 2010, I thought control structures like if/then statements, along with for and while loops, were relatively boring features of programming languages, but that was only because I didn’t know there was another way. These days I know that they’re a defining feature of programming languages.
Scala’s control structures are:
-
forloops andforexpressions -
if/then/else ifexpressions -
matchexpressions (pattern matching) -
try/catch/finallyblocks -
whileloops
I’ll briefly introduce each of these next, and then the recipes will show you additional details about how to use their features.
for Loops and for Expressions
In their most basic use, for loops provide a way to iterate over a collection to operate on the collection’s elements:
fori<-List(1,2,3)doprintln(i)
But that’s just a basic use case. for loops can also have guards—embedded if
statements:
fori<-1to10ifi>3ifi<6doprintln(i)
With the use of the yield keyword, for loops also become for expressions—loops that yield a result:
vallistOfInts=fori<-1to10ifi>3ifi<6yieldi*10
After that loop runs, listOfInts is a Vector(40, 50). The guards inside the loop filter out all of the values except 4 and 5, and then those ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access