Explain the functionality of Yield in Scala

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-27 08:02:15 Viewed : 288


Explain the functionality of Yield in Scala?

In Scala, yield is a keyword used in conjunction with a for comprehension to produce a collection as the result of a transformation or filtering operation. It allows you to create a new collection by applying a transformation or filtering function to each element of an existing collection, and the results are collected into a new collection of the same type. This feature is often used to create concise and readable code when working with collections.

Here is the basic syntax of a for comprehension with yield:

scala
val result = for (element <- collection) yield { // Transformation or filtering logic // Resulting value (will be added to the new collection) }

The yield keyword is used inside the for comprehension to specify the transformation or filtering logic. The result of this logic is automatically collected into a new collection, which is then assigned to the result variable.

Here is an example to illustrate the functionality of yield:

scala
val numbers = List(1, 2, 3, 4, 5) val doubledNumbers = for (num <- numbers) yield { num * 2 } // doubledNumbers is now a List(2, 4, 6, 8, 10)

In this example, we have a list of numbers. The for comprehension with yield is used to create a new list, doubledNumbers, where each element is twice the value of the corresponding element in the numbers list. The result is a new list containing [2, 4, 6, 8, 10].

Key points to understand about yield in Scala:

  1. yield transforms or filters elements from an existing collection and produces a new collection of the same type.

  2. The type of the resulting collection is determined by the type of the collection you iterate over. For example, if you iterate over a List, the result will be a new List.

  3. The for comprehension can include additional conditions and nested comprehensions for more complex operations.

  4. You can use pattern matching and other expressions within the yield block to calculate the values for the new collection.

yield is a powerful and expressive feature in Scala that simplifies the process of creating transformed or filtered collections, making your code more concise and readable when working with collections.

Search
Related Articles

Leave a Comment: