Scala: For Loop
- Harini Mallawaarachchi
 - Mar 21, 2023
 - 1 min read
 
The for loop is an efficient way to write a loop that needs to be repeated a certain number of times. A for loop can be written in various ways in Scala, as follows:
Syntax − for loop with ranges
The simplest syntax.
for( var x <- Range ){
   statement(s);
}examples:
for( a <- 1 to 10){for( a <- 1 to 3; b <- 1 to 3){for( a <- 1 until 10){Syntax − for Loop with Collections
for( var x <- List ){
   statement(s);
}Syntax − for loop with Filters
for( var x <- List
      if condition1; if condition2...
   ){
   statement(s);
}Syntax − for loop with yield
"For" loop return values can be stored in variables or returned through functions. Yield is used as a prefix to the body of 'for' Loop.
var retVal = for{ var x <- List
   if condition1; if condition2...
}
yield xexample:
var retVal = for{ a <- numList if a != 3; if a < 8 }yield a

Comments