If Expression
Like many other programming languages Scala if expression
is not the same. After the execution of the code, if statements are expressions meaning that they return a value. Hence, this can be written in the following two ways:
or
Loops
Scala’s while loop
behave the same like Java and C#. Scala while loop has a condition and a body. According to the condition the body context will keep on looping.
Scala also has do-while loop
. Like while loop it will keep on looping until the condition is true.
Scala’s for loop
expression is bit different. It has some fancy way of implementing with arrow syntax to iterate through the collection dataset.
The above loop functionality you may have come across in Java and C#. But Scala for loop offers a lot more feature like filter, nested loop and yield.
Filtering
We some times do not want to iterate through the entire collection data and we need to break down in to a small subset. So scala provide the freedom to do that by adding condition as filter.
The following above code consist a Fish
class with the attribute fish name and whether it’s a beautiful fish. In the next line list of seaFish
is created and during the iteration process ugly catfish
fishes are filtered.
Nested loops
There can be a situation where you will need to iterate through a collection where it consists of another collection list. Basically it’s a nested collection data. Scala provides a great feature to run through the collection data with one for loop ☺.
You have come to a stage where you need to manipulate and analyse with two or more groups of dataset. The following below code shows clearly while iterating through fish list
include the lakeFish
list in an effective way.
Yielding
Using the yield keyword with for loop
expressions, can create and return new collections data set.
To understand the yield functionality lets take the fish example the ‘seaFish’ list object and during the for loop iteration process use the yield
keyword to append ‘new’ string value in front of all the sea fish names. So it will append and create a new collections list (Figure 1)