Go Back

Loop in scala 

4/9/2023
All Articles

#Loop in scala  , #for loop , #while loop , #example of variant of for loop

Loop in scala 

Loop in scala 

Most fundamental ways to perform iteration  on given set of input that  is called loop.

There is mostly 2 type of Loop:-

  • While
  • For
  • do while

While is as much simple we learn in  other programming language like c , java .
But in scala we can able to see varient in FOR LOOP.

In for loop is used to iterate over a range of values or collections in Scala.

  1. Numeric Range:
  2. collection
a) Numeric Range:
 
 
     for (i <- 1 to 5) {
           println(s"Value of i: $i")
     }
 
b) Collections:
 
     val fruits = List("Apple", "Banana", "Orange")
     for (fruit <- fruits) {
     println(s"Current fruit: $fruit")
     }
 
 
While Loop is used to repeat a block of code as long as a certain condition is true or false.
 
var i = 1
while (i <= 5) {
  println(s"Value of i: $i")
  i += 1
}
 
The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition.
 
  var i = 1
  do {
    println(s"Value of i: $i")
    i += 1
   } while (i <= 5)
 


Type of for loop  

  •  Imperative
  •  functional

Below is example of  styles are decidedly imperative in scala .
for (
number <- numbers
if (number % 2 == 0)
if (number > 2)
) println(number)
 

In this example we can handle mutiple for  loop : 


for (number <- numbers){
for ( letter <- letters){
println(number +" =>"+letter )
}
}

Or we can simplify the above example and using one loop for two array or list.

for (
number <- numbers
letter <- letters
) println(number)

 

Functional for loop :

It is define as function because we use some collection copy algorithum for this loop .

we used Yield keyword for  copy collection into final variable.

 

 

for (number <- numbers ) yield {number *2}

for {number <- numbers
letter <- letters
} yield number + "=>" + letter

 

Conclusion 

For functional programming, using for comprehensions and higher-order functions

like map, filter, flatmap and fold is often preferred over traditional loops.

Here we see  loops in scala and it variant that is just simplify our doubt and question.

Article