Loop in scala
For loop in Scala example #Loop in scala #for loop , #while loop , #example of variant of for loop
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:
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
}
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)
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:
for (i <- 1 to 5) {
println(s"Value of i: $i")
}
val fruits = List("Apple", "Banana", "Orange")
for (fruit <- fruits) {
println(s"Current fruit: $fruit")
}
val numbers = List(1, 2, 3, 4, 5)
for (
number <- numbers
if (number % 2 == 0)
if (number > 2)
) println(number)
val numbers = List(1, 2, 3)
val letters = List('A', 'B', 'C')
for (number <- numbers; letter <- letters) {
println(number + " => " + letter)
}
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)
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!