Loop in scala 

4/8/2023

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

Go Back

Loops in Scala: A Complete Guide

Loops are one of the most fundamental ways to perform iteration on a given set of inputs. In Scala, there are primarily three types of loops:

  • While Loop
  • For Loop
  • Do-While Loop
For loop in Scala example #Loop in scala  #for loop , #while loop , #example of variant of for loop

1. While Loop in Scala

The while loop is used to repeat a block of code as long as a certain condition is true. Here's an example:


var i = 1
while (i <= 5) {
  println(s"Value of i: $i")
  i += 1
}
    

2. Do-While Loop in Scala

The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition. Here's an example:


var i = 1
do {
  println(s"Value of i: $i")
  i += 1
} while (i <= 5)
    

3. For Loop in Scala

The for loop in Scala is more powerful and flexible compared to other languages. It can iterate over ranges, collections, and more. Here are some examples:

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")
}
    

c) Multiple Conditions in For Loop


val numbers = List(1, 2, 3, 4, 5)
for (
  number <- numbers
  if (number % 2 == 0)
  if (number > 2)
) println(number)
    

d) Nested For Loop


val numbers = List(1, 2, 3)
val letters = List('A', 'B', 'C')
for (number <- numbers; letter <- letters) {
  println(number + " => " + letter)
}
    

4. Functional For Loop with Yield

Scala supports functional loops using the yield keyword. This allows you to create a new collection from an existing one. Here's an example:


val numbers = List(1, 2, 3, 4, 5)
val doubledNumbers = for (number <- numbers) yield { number * 2 }
println(doubledNumbers) // Output: List(2, 4, 6, 8, 10)
    

Conclusion

The for loop in Scala is more powerful and flexible compared to traditional loops in other languages. It can iterate over ranges, collections, and more. While traditional loops like for and while are available, functional programming techniques like for comprehensions and higher-order functions (map, filter, flatMap, and fold) are often preferred in Scala.

By understanding these loop constructs, you can write more efficient and expressive Scala code. Happy coding!

Table of content