Scala | yield Keyword
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer. It doesn’t work like imperative loop. The type of the collection that is returned is the same type that we tend to were iterating over, Therefore a Map yields a Map, a List yields a List, and so on.
Syntax:
var result = for{ var x <- List}
yield x
Note: The curly braces have been used to keep the variables and conditions and result is a variable wherever all the values of x are kept within the form of collection.
Example:
// Scala program to illustrate yield keyword // Creating object object GFG { // Main method def main(args: Array[String]) { // Using yield with for var print = for( i <- 1 to 10) yield i for(j<-print) { // Printing result println(j) } } } |
Output:
1 2 3 4 5 6 7 8 9 10
In above example, the for loop used with a yield statement actually creates a sequence of list.
Example:
// Scala program to illustrate yield keyword // Creating object object GFG { // Main method def main(args: Array[String]) { val a = Array( 8, 3, 1, 6, 4, 5) // Using yield with for var print=for (e <- a if e > 4) yield e for(i<-print) { // Printing result println(i) } } } |
Output:
8 6 5
In above example, the for loop used with a yield statement actually creates a array. Because we said yield e, it’s a Array[n1, n2, n3, ....]. e <- a is our generator and if (e > 4) could be a guard that filters out number those don't seem to be greater than 4.
Recommended Posts:
- Scala short <(x: Short): Boolean
- Scala short <(x: Char): Boolean
- Scala Extractors
- Scala | Partially Applied functions
- Scala String indexOf(String str) method with example
- Scala String contentEquals() method with example
- Scala Keywords
- Scala Int /(x: Int) method with example
- Scala Int /(x: Short) method with example
- Program to print Java Set of characters in Scala
- Scala Map size() method with example
- Scala SortedMap addString() method with a start, a separator and an end with example
- Scala Iterator addString() method with example
- Scala String substring(int beginIndex, int endIndex) method with example
- Scala | Functions Call-by-Name
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


