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.

+3


source to share


3 answers


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.

+4


source


Answer # 2: You can case

only use curly braces. A more complete answer about curly braces is here .



+1


source


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)

      

0


source







All Articles