Loop in scala
#Loop in scala #for loop , #while loop , #example of variant of for loop
Most fundamental ways to perform iteration on given set of input that is called loop.
There is mostly 2 type of Loop:-
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.
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
The for loop in Scala is similar to those in other languages but is more powerful and flexible. It can iterate over ranges, collections, and more. while traditional loops like for and while are available and sometimes useful. 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.