Scala - Yield Keyword



You can store return values from a "for" loop in a variable or can return through a function. To do so, you prefix the body of the 'for' expression by the keyword yield.

Syntax

The following is the syntax to use yield keyword −

var retVal = for {
   var x <- List
   if condition1
   if condition2
   ...
} yield x

Note − the curly braces have been used to keep the variables and conditions and retVal is a variable where all the values of x will be stored in the form of collection.

Example of Scala Yield Keyword

Try the following example program to understand loop with yield −

object Demo {
   def main(args: Array[String]) {
      var a = 0
      val numList = List(1,2,3,4,5,6,7,8,9,10)

      // for loop execution with a yield
      var retVal = for { 
        a <- numList 
        if a != 3
        if a < 8 
      } yield a

      // Now print returned values using another loop.
      for (a <- retVal) {
         println("Value of a: " + a)
      }
   }
}

In the above example, we have first filtered the element using condition a != 3; and a < 8. So it will select only elements that are not equal to 3 and are less than 8. Now, yield keyword is used to collect the selected elements into a new list retVal. The second for loop iterates over retVal and prints each element.

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

value of a: 1
value of a: 2
value of a: 4
value of a: 5
value of a: 6
value of a: 7

Doubling Elements Using Yield Keyword

Use yield to double each element in a list −

object DoubleDemo {
   def main(args: Array[String]) = {
      val numbers = List(1, 2, 3, 4, 5)
      val doubled = for (n <- numbers) yield n * 2

      println(doubled)  // Output: List(2, 4, 6, 8, 10)
   }
}

In this example, the yield keyword takes each element n from numbers, doubles it (n * 2), and collects the results into a new list doubled.

Save the above program in DoubleDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac DoubleDemo.scala
\>scala DoubleDemo

Output

List(2, 4, 6, 8, 10)

Creating pairs from two lists and computing their products.

object ProductDemo {
   def main(args: Array[String]) = {
      val list1 = List(1, 2, 3)
      val list2 = List(4, 5, 6)
      val products = for {
        a <- list1
        b <- list2
      } yield a * b

      println(products)  // Output: List(4, 5, 6, 8, 10, 12, 12, 15, 18)
   }
}

In this example, for each element a from list1 and each element b from list2, their product a * b is computed and collected into the products list.

Save the above program in ProductDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac ProductDemo.scala
\>scala ProductDemo

Output

List(4, 5, 6, 8, 10, 12, 12, 15, 18)
Advertisements