277 total views, 2 views today
Welcome to Scala series. In this tutorial, you will learn about Scala yield function.
Scala yield function is used along with for loop comprehensions. Yield function is used for storing data/element of each iteration in a collection.
For each iteration of the for loop, yield function helps to store each element in the backend in a buffer or in memory and once the for loop finishes it produces a list of elements yielded.
Let us see an example.
scala> for(i <- 1 to 20 if i % 2 == 0) yield(i) res15: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
In the above example, we are iterating over a range of 1 to 20, filter out only even number and pass the element to the yield function.
Once the for loop is completed, it has generated a collection of even number that was yielded in the for loop. The type of collection is Vector in this case.
scala> val x = for(i <- 1 to 20 if i % 2 == 0) yield(i) x: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
In the above example, we are doing the same operation but storing the output in variable x and it of type Vector.
How the type of yield output is decided?
The type of the output collection is the same as the type of collection iterated over by for loop.
If the iteration is performed on Array[Int] then the yielded collection type will also be Array[Int].
So an Array yields an array.
A list yields a list
A map yields a map.
yield function is used in combination with for loops to store each element of the collection in a separate collection. The type of yielded collection is the same as the type of input collection.
References: Official documentation
Hope this tutorial was helpful. Please leave a comment and give us a thumbs up!.