In scala foreach loop if I have list
val a = List("a","b","c","d")
I can print them without a pattern matching like this
a.foreach(c => println(c))
But, if I have a tuple like this
val v = Vector((1,9), (2,8), (3,7), (4,6), (5,5))
why should I have to use
v.foreach{ case(i,j) => println(i, j) }
Please explain what happens when the two foreach loops are executed.
Scala Map foreach() method with exampleThe foreach() method is utilized to apply the given function to all the elements of the map. Return Type: It returns all the elements of the map after applying the given function to each of them. So, the identical elements are taken only once.
A simple for loop that iterates over a collection is translated to a foreach method call on the collection. A for loop with a guard (see Recipe 3.3) is translated to a sequence of a withFilter method call on the collection followed by a foreach call.
You don't have to, you choose to. The problem is that the current Scala compiler doesn't deconstruct tuples, you can do:
v.foreach(tup => println(tup._1, tup._2))
But, if you want to be able to refer to each element on it's own with a fresh variable name, you have to resort to a partial function with pattern matching which can deconstruct the tuple.
This is what the compiler does when you use case
like that:
def main(args: Array[String]): Unit = {
val v: List[(Int, Int)] = scala.collection.immutable.List.apply[(Int, Int)](scala.Tuple2.apply[Int, Int](1, 2), scala.Tuple2.apply[Int, Int](2, 3));
v.foreach[Unit](((x0$1: (Int, Int)) => x0$1 match {
case (_1: Int, _2: Int)(Int, Int)((i @ _), (j @ _)) => scala.Predef.println(scala.Tuple2.apply[Int, Int](i, j))
}))
}
You see that it pattern matches on unnamed x0$1
and puts _1
and _2
inside i
and j
, respectively.
According to http://alvinalexander.com/scala/iterating-scala-lists-foreach-for-comprehension:
val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
for (name <- names)
println(name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With