Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 03:18:08 Viewed : 799
In Scala, the for
loop is a powerful construct that can be used for iterating over collections and sequences. When combined with yield
, it becomes a powerful tool for creating new collections by transforming or filtering elements from existing ones.
Here is the basic syntax of a for
loop with yield
:
scalaval result = for (element <- collection) yield { // Transformation or filtering logic transformedElement }
collection
: This is the collection you want to iterate over, such as an Array
, List
, or Range
.
element
: This represents each element of the collection as you iterate over it.
transformedElement
: This is the result of applying some transformation or filtering logic to the element
. You can perform operations on element
and produce a new value.
result
: This is the resulting collection that will hold the transformed or filtered elements.
Here is an example to illustrate how a for
loop with yield
works:
scalaval numbers = List(1, 2, 3, 4, 5) val doubledNumbers = for (num <- numbers) yield { num * 2 } println(doubledNumbers)
In this example, we have a list of numbers, and we want to create a new list called doubledNumbers
where each element is doubled. The for
loop with yield
takes each element from the numbers
list, multiplies it by 2, and adds the result to the doubledNumbers
list.
Output:
scssList(2, 4, 6, 8, 10)
The for
loop with yield
is a concise way to create a new collection based on the elements of an existing collection, while also applying a transformation or filtering operation. Its often used when you want to perform such operations on all elements of a collection and collect the results into a new collection.
for loops
and expressions syntax as follows
·
for
loop with block syntax
for( i <- range){
// statements to be executed
}
· for loop without block syntax
for (arg <- args) println(arg)
· for loop with "x to y" syntax
for (i <- 0 to 5) println(i)
· for loop “x to y by" syntax
for (i <- 0 to 10 by 2) println(i)
yield keword
You
can also add the yield keyword to for-loops to create for-expressions that yield
a result. Here is a for-expression that doubles each value in the sequence 1 to 5:
val x = for (i <- 1 to 5) yield i * 2
For each iteration
of your for loop, yield generates a value which will be remembered. Its like
the for loop has a buffer you cant see, and for each iteration of your for
loop another item is added to that buffer.
so a Map yields a Map, a List
yields a List, and so on.
Example:
Following example illustrates about Scala for loop and Yield
Save the file as − ForLoopAndYield.scala
package runnerdev
object ForLoopAndYield extends App {
for (x <- 0 to 5) { //range expression
println("x " + x)
}
for (i <- 0 to 10 by 2) {
println("x to y by
" + i)
}
val multiVal = for (i <- 1 to 5) yield i * 2
println("multiVal " + multiVal);
//for-expression
that iterates over a list of strings
val animals = List("ant", "bat", "cat", "elephant")
val animalLengths = for {
f <- animals
if f.length > 4
} yield f.length
}
compile
and run the above example as follows
scala> scalac ForLoopAndYield.scala
scala> scala ForLoopAndYield
OutPut:
x 0
x 1
x 2
x 3
x 4
x 5
x to y by 0
x to y by 2
val colors = List("red", "green", "blue") val fruits = List("apple", "banana", "cherry") val combinations = for { color <- colors fruit <- fruits } yield { s"$color $fruit" } combinations.foreach(println)
Output:
red apple red banana red cherry green apple green banana green cherry blue apple blue banana blue cherry
In this example, we use nested for
loops with yield
to create combinations of colors and fruits. Each combination is stored as a string in the combinations
list.
Example 4: Generating a Sequence
scalaval squares = for (x <- 1 to 5) yield { x * x } println(squares)
Output:
scssVector(1, 4, 9, 16, 25)
Here, we generate a sequence of squares from 1 to 5 using a for
loop with yield
.
These examples demonstrate how you can use for
loops with yield
to transform or filter elements in collections, create new collections, and generate sequences based on existing data.
In Scala, yield
is used within a for
comprehension to produce a new collection by applying transformations or filters to the elements of an existing collection. Essentially, it allows you to create a new collection from an existing one while specifying how each element should be transformed or filtered.
Here is the basic syntax of a for
comprehension with yield
:
scalaval result = for (element <- collection) yield { // Transformation or filtering logic transformedElement }
collection
: The collection you want to iterate over.
element
: Represents each element of the collection as you iterate over it.
transformedElement
: The result of applying some transformation or filtering logic to element
.
result
: The resulting collection that holds the transformed or filtered elements.
Here is an example:
scalaval numbers = List(1, 2, 3, 4, 5) val squaredNumbers = for (num <- numbers) yield { num * num }
In this example, the for
comprehension iterates over each element (num
) in the numbers
list and squares each element. The result is a new list called squaredNumbers
containing the squared values.
Output:
scssList(1, 4, 9, 16, 25)
The yield
keyword is especially useful when you want to apply a transformation to each element in a collection and collect the results into a new collection. It helps make your code more concise and readable.
You can also use if
conditions within the for
comprehension to filter elements:
scalaval numbers = List(1, 2, 3, 4, 5) val evenNumbers = for (num <- numbers if num % 2 == 0) yield { num }
In this case, only even numbers are included in the evenNumbers
list.
Output:
scssList(2, 4)
By combining for
and yield
, you can perform various transformations and filters on collections, making your code more expressive and functional.
with yield and without yield in scala examples:
In Scala, you can use for
comprehensions both with and without yield
to achieve different results. When you use yield
, the for
comprehension produces a new collection, while without yield
, its used for performing side-effects or iterating through a collection without creating a new one. Here are examples of both cases:
With yield
:
scalaval numbers = List(1, 2, 3, 4, 5) // Using yield to create a new list with squared numbers val squaredNumbers = for (num <- numbers) yield { num * num } println(squaredNumbers)
In this example, we use yield
to create a new list, squaredNumbers
, containing the squares of the elements from the numbers
list.
Output:
scssList(1, 4, 9, 16, 25)
Without yield
:
scalaval numbers = List(1, 2, 3, 4, 5) // Without yield, performing a side-effect (printing each element) for (num <- numbers) { println(num) }
In this example, we dont use yield
, so the for
comprehension is used for its side-effect, which is printing each element of the numbers
list.
Output:
1 2 3 4 5
In the second example, the for
comprehension is used primarily for its iteration capability, and it doesnt produce a new collection. Its often used when you want to perform some action for each element in a collection without creating a new collection as a result.
With yield
, you transform or filter elements from a collection and create a new collection with the results. Without yield
, you can perform actions or side-effects on each element during the iteration.