scala yield how to share one loop
In Scala, you can use the yield
keyword to create a new collection by applying a transformation to each element of an existing collection. To share one loop among multiple yield
expressions, you can use a for comprehension.
Here's an example of how you can share one loop using yield
in Scala:
val numbers = List(1, 2, 3, 4, 5)
val result = for {
number <- numbers
multiplied = number * 2
squared = multiplied * multiplied
} yield squared
// result: List(4, 16, 36, 64, 100)
In this example, we have a list of numbers. We use a for comprehension to iterate over each number in the list. Inside the for comprehension, we define two new variables: multiplied
, which is the number multiplied by 2, and squared
, which is the result of multiplying multiplied
by itself. The yield
keyword is used to create a new collection with the squared values.
The resulting collection result
will contain the squared values of each number in the original list.
Note that the yield
keyword is optional in Scala. If you don't specify it, the for comprehension will return a Unit
value.