Foreach loop in scala
In scala a foreach loop if i have a list
val a = List("a","b","c","d")
I can print them without a template matching 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 use
v.foreach{ case(i,j) => println(i, j) }
- pattern matching example
- {brackets
Please explain what happens when two foreach loops are executed.
source to share
You don't need, you choose. The problem is that the current Scala compiler does not deconstruct tuples, you can do:
v.foreach(tup => println(tup._1, tup._2))
But if you want to be able to reference every element on it with a fresh variable name, you need to resort to a partial function with pattern matching that can deconstruct the tuple.
This is what the compiler does when you use it case
like this:
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 can see that the template matches the unnamed one x0$1
and puts _1
both _2
inside i
and out j
accordingly.
source to share
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)
source to share