In Scala, the ‘yield‘ keyword is used in conjunction with for-comprehensions to return a new collection by applying some transformation on each element of the original collection. The purpose of ‘yield‘ is to allow a concise and readable syntax for performing this transformation.
A for-comprehension with ‘yield‘ has the following general form:
for (pattern <- c1;
pattern2 <- c2; ...
if condition) yield expression
Here, ‘c1‘, ‘c2‘ are collections, and ‘expression‘ represents the transformation on those collections’ elements.
Each iteration through the collections, the ‘expression‘ is evaluated and added to the resulting new collection. The type of the new collection will be the same as the original collection, following Scala’s best effort to preserve the type.
Here is an example:
val numbers = List(1, 2, 3, 4, 5)
val squaredNumbers = for (n <- numbers) yield n * n
In this example, ‘numbers‘ is a ‘List[Int]‘, and the for-comprehension iterates through each element ‘n‘ in ‘numbers‘, then evaluates the expression ‘n * n‘ (which squares each element), and stores the result in a new collection ‘squaredNumbers‘. The type of ‘squaredNumbers‘ will also be ‘List[Int]‘, and its value will be ‘List(1, 4, 9, 16, 25)‘.
The use of ‘yield‘ in this case allows for a more readable and concise syntax compared to using a combination of ‘map‘, ‘flatMap‘, and ‘filter‘ methods.
You can also use ‘yield‘ with additional generators and conditions, like this:
val matrix = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
val evenNumbers = for {
row <- matrix
number <- row
if number % 2 == 0
} yield number
In this example, the ‘evenNumbers‘ variable will have the value ‘List(2, 4, 6, 8)‘ after the for-comprehension. Here, we have two generators (‘row <- matrix‘, ‘number <- row‘) and a condition to filter out odd numbers (‘if number