Scala Control Structures

By: Stephen Patrick | 03 Aug 2016 | Category: Scala Language Basics

Related Contents

Scala Control Structures

Scala provides a number of different control structures. Scala provides the if / else control structure that is the same as used in most programming languages. Scala also provides a number of iterative control structures such as for, and while loops.

Scala If Else Block

The Scala if / else block is the same as in most other programming languages if the expression evaluates to true the if block is executed otherwise, the else block is executed.

if(true) {
   print(True)
} else {
   print(False)
}

Scala While Loop

The Scala while loop executes the block of code while the expression evaluates to true.

var i  = 0;
while(i<10) {
   println (i)
   i += 1
}

Scala For Comprehension

Scala provides a flexible for structure that allows you to perform an operation N number of times. Scala provides different variants on how a for structure can be created.

import Array._
var array = range(1,10)

for(i <- array) {
   println(i)
}

The above code uses a range to create an array of integers with the value between 1 - 9 inclusive. The <- symbol is known as a generator as it is used to generate individual values from a range. The above code outputs:

1
2
3
4
5
6
7
8
9

A similar operation can be performed in other ways for example we can use to and until to enumerate a range of values.

for(i <- 1 to 10) {
   println(i)
}

Outputs:

1
2
3
4
5
6
7
8
9
10

We can also use until to enumerate a range of values

for(i <- 1 until 10) {
   println(i)
}

The above code outputs the range 1 to 9 inclusive.

1
2
3
4
5
6
7
8
9

The for construct can also take multiple enumerators for example:

for(i <- 1 until 4;  j <- 1 until 4 ) {
   println( "Value of i: " + i );
   println( "Value of j: " + j );
}

Outputs:

Value of i: 1
Value of j: 1
Value of i: 1
Value of j: 2
Value of i: 1
Value of j: 3
Value of i: 2
Value of j: 1
Value of i: 2
Value of j: 2
Value of i: 2
Value of j: 3
Value of i: 3
Value of j: 1
Value of i: 3
Value of j: 2
Value of i: 3
Value of j: 3

The for structure can also use filters for example:

import Array._
var array = range(1,10)

for(i <- array; if i <= 5) {
   println(i)
}

Outputs:

1
2
3
4
5

For Generators

The for construct also allows you to produce generators similar in a way to generators in Python. Instead of iterating through all of the elements we can use the yield keyword to return a single value on each iteration. When the for expression completes we can consider the output to be like a new collection that we can iterate.

var newArray = 
   for(i <- 1 to 5) yield i + 2

Outputs

newArray: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 4, 5, 6, 7)

We can then iterate it:

for (i <- newArray) {
   println(i)
}