Scala Control Structures – A Comprehensive Guide 1


1. Objective

This Scala tutorial will help you in learning Scala programming language using Scala Control structures with syntax. You will understand how to write Scala programs using Scala if else function, for loop in Scala, Match expressions in scala and while or do while loop in scala along with scala examples.

Before starting with control structures in Scala, let us understand Scala basics for beginners and features of Scala that make it programmers choice.

SCALA CONTROL STRUCTURES

2. Scala control structures

Do you know what is control structure?

A control structure is a block of programming that analyzes variables and selects how to proceed based on given parameters. It is the basic decision-making process in computing that determines the program flow based on certain conditions and parameters.

So let us see various types of control structures used in Scala.

a. if…Else Control Structure

The If..Else conditional expression is a classic programming construct for choosing a branch of code based on whether an expression resolves to true or false. In many languages it starts with an “if,” continues with zero to many “else if ” sections, and ends with a final “else” catch-all statement.

Syntax: Using an If Expression

if (<Boolean expression>) <expression>

The term Boolean expression here indicates an expression that will return either true or false. Below is if block that prints a notice if the Boolean expression is true:

scala> if ( 47 % 3 > 0 ) println(“Not a multiple of 3”)

Not a multiple of 3

Of course 47 isn’t a multiple of 3, so the Boolean expression was true and the println was triggered.

Although if block can act as an expression, it is better suited for statement like this. The problem with using if block as expression is that they only conditionally return a value. If the Boolean expression returns false, what do you expect if block to return?

Syntax: If .. Else Expressions

if (<Boolean expression>) <expression>
else <expression>

 

Example:

scala > val x = 10; val y = 20
x: Int = 10
y: Int = 20
scala > val max = if (x > y) x else y
max: Int = 20

Here x and y values make up the entirety of if and else expressions. The resulting value is assigned to max, which we and the Scala compiler know will be an Int because both expressions have return values of type Int. You can use it like a Java ternary operator:

 

val absValue = if (a < 0) -a else a // ternary

println(if (i == 0) "a" else "b") // in println

hash = hash * prime + (if (name == null) 0 else name.hashCode) // in equation

def abs(x: Int) = if (x >= 0) x else -x // as a method body

b. Match Expression

Match expressions are similar to “switch” statements of C and Java, in which a single input item is checked and the first pattern that is “matched” is executed and its value returned. Like “switch” statement of C and Java, match expressions in Scala support a default “catch-all” pattern. Unlike them, in match expressions only zero or one patterns can match. There is no break statement or “fall-through” from one pattern to the next one in line that would prevent this fall-through.

Syntax: 

<expression> match {
case <pattern match> => <expression>
[case...]
}

Example:

val month = i match {
case 1 => "January"
case 2 => "February"
case 3 => "March"
case 4 => "April"
case 5 => "May"
case 6 => "June"
case 7 => "July"
case 8 => "August"
case 9 => "September"
case 10 => "October"
case 11 => "November"
case 12 => "December"
case _ => "Invalid month" // the default, catch-all
}

Match expression in function body for different type value:

def getClassAsString(x: Any):String = x match {
case s: String => s + " is a String"
case i: Int => "Int"
case f: Float => "Float"
case l: List[_] => "List"
case p: Person => "Person"
case _ => "Unknown"
}

use ‘if’ expressions in case statements

i match {
case a if 0 to 9 contains a => println("0-9 range: " + a)
case b if 10 to 19 contains b => println("10-19 range: " + a)
case c if 20 to 29 contains c => println("20-29 range: " + a)
case _ => println("Hmmm...")
}

reference class fields in your ‘if’ statements:

stock match {
case x if (x.symbol == "XYZ" && x.price < 20) => buy(x)
case x if (x.symbol == "XYZ" && x.price > 50) => sell(x)
case x => doNothing(x)
}

c. For Loop

A loop is a term for exercising a task repeatedly and may include iterating through a range of data or repeating until a Boolean expression returns false.

The most important looping structure in Scala is the for-loop which is also called “for comprehension”. For loops in scala can iterate over a range of data executing an expression every time and optionally return values that is a collection of all the expression’s return values. These loops are highly supporting nested iterating, filtering, value binding and are customizable.

Examples:

// simple for loops

for (arg <- args) println(arg)
for (i <- 0 to 5) println(i)
for (i <- 0 to 10 by 2) println(i) 

// for loop with multiple counters:

scala > for (i <- 1 to 2; j <- 1 to 2) printf("i = %d, j = %d\n", i, j)
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2

// print all even numbers by adding a ‘guard’

scala > for (i <- 1 to 10 if i % 2 == 0) println(i)
2
4
6
8
10

// multiple guards

for {
file <- files
if passesFilter1(file) // guard
if passesFilter2(file) // guard
} doSomething(file) 

// for loop with guard and yield

for {
file <- files
if hasSoundFileExtension(file)
if !soundFileIsLong(file)
} yield file

// more for loops with ‘yield’

 val a = Array("apple", "banana", "orange") // Array(apple, banana, orange)
val newArray = for (e <- a) yield e.toUpperCase // Array(APPLE, BANANA, ORANGE)
val a = Array(1, 2, 3, 4, 5) // Array(1, 2, 3, 4, 5)
for (e <- a) yield e // Array(1, 2, 3, 4, 5)
(e <- a) yield e * 2 // Array(2, 4, 6, 8, 10)
for (e <- a) yield e % 2 // Array(1, 0, 1, 0, 1)
for (e <- a if e > 2) yield e // Array(3, 4, 5) 

d. While loop / Do..while loop

In addition to for-loop, “while” and “Do..While” loops are also being supported by Scala. They repeat a statement until false is returned by Boolean expression. These are not as commonly used as for-loops in scala, however, because they are not expressions and cannot be used to yield values.

Syntax of While Loop:

while (<Boolean expression>) statement

Example:

var i = 0
while (i < array.length) {
println(array(i))
i += 1
}

The do..While loop is similar but the statement is executed before the Boolean expression is first evaluated. In this example we have a boolean expression that will return false, but is only checked after the statement has had a chance to run –

Syntax of Do While loop in Scala:

do {// expression…} while (condition)

Example:

val x = 0
do println("Here I am, x = $x") while (x > 0) // Here I am, x = 0

Source:

https://www.scala-lang.org/


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Scala Control Structures – A Comprehensive Guide