Google News
logo
Scala - Interview Questions
What is the purpose of the 'yield' keyword in a generator expression in Scala?
In Scala, the `yield` keyword is used in a generator expression to construct a collection based on the elements generated by the expression. It allows you to transform and filter the elements produced by the generator expression and collect them into a new collection.

A generator expression is defined using the `for` comprehension syntax, which combines `yield` with one or more generator clauses and optional filter conditions. The `yield` keyword specifies the expression to be generated for each element produced by the generators and filters.

Here's an example to illustrate the use of `yield` in a generator expression :
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, we have a list of numbers `[1, 2, 3, 4, 5]`. Using the `for` comprehension with `yield`, we iterate over each element in the `numbers` list, and for each element `n`, we yield `n * 2`. The result is a new list `doubled` that contains the doubled values of the original numbers.

The `yield` keyword captures the generated values and constructs a new collection of the same type as the generator expression. In this case, the generator expression is based on a list, so the result is also a list. However, the type of the result can vary depending on the type of the generator expression.

The `yield` keyword is useful when you want to transform or filter the elements produced by a generator expression and collect the results into a new collection. It provides a concise and readable way to express such transformations, making your code more expressive and maintainable.
Advertisement