top of page
Writer's pictureHarini Mallawaarachchi

Scala: For Loop

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 x

example:

var retVal = for{ a <- numList if a != 3; if a < 8 }yield a

0 views0 comments

Recent Posts

See All

Scala: Define variables

Compilers allocate memory and decide what can be stored in reserved memory based on variables' data types. As a result, you can store...

Comments


bottom of page