Scala for-loop and yield

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 08:48:08 Viewed : 213


Scala for-loop and yield

for loops and expressions syntax as follows

 ·        for loop with block syntax 

for( i <- range){  

    // statements to be executed  

}      

·        for loop without block syntax 

for (arg <- args) println(arg)     

·        for loop with "x to y" syntax

for (i <- 0 to 5) println(i) 

·        for loop “x to y by" syntax 

for (i <- 0 to 10 by 2) println(i) 

yield keword 

You can also add the yield keyword to for-loops to create for-expressions that yield a result. Here’s a for-expression that doubles each value in the sequence 1 to 5:

val x = for (i <- 1 to 5) yield i * 2 

For each iteration of your for loop, yield generates a value which will be remembered. Its like the for loop has a buffer you can’t see, and for each iteration of your for loop another item is added to that buffer.

so a Map yields a Map, a List yields a List, and so on.    

Example:

Following example illustrates about Scala for loop and  Yield

Save the file as − ForLoopAndYield.scala

 ForLoopAndYield.scala  //File name

package runnerdev

object ForLoopAndYield extends App { 

  for (x <- 0 to 5) { //range expression 

    println("x " + x)

  }

   // "x to y by"

  for (i <- 0 to 10 by 2) {

    println("x to y by " + i)

  }

  //yield keyword -for-expression that doubles each value in the   sequence 1 to 5

  val multiVal = for (i <- 1 to 5) yield i * 2

  println("multiVal " + multiVal); 

  //for-expression that iterates over a list of strings

  val animals = List("ant", "bat", "cat", "elephant") 

  val animalLengths = for {

    f <- animals

    if f.length > 4

  } yield f.length

  println("animalLengths " + animalLengths);

}

compile and run the above example as follows 

scala> scalac ForLoopAndYield.scala

scala> scala ForLoopAndYield

OutPut:

x 0

x 1

x 2

x 3

x 4

x 5

x to y by 0

x to y by 2

Search
Sub-Categories
Related Articles

Leave a Comment: