Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop in scala

Tags:

foreach

scala

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) }
  1. a pattern matching case
  2. { brackets

Please explain what happens when the two foreach loops are executed.

like image 555
Srinivas Avatar asked Jul 18 '17 11:07

Srinivas


People also ask

How does Scala foreach loop work?

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.

Which expression is one way to iterate over a collection in Scala?

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.


2 Answers

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.

like image 157
Yuval Itzchakov Avatar answered Oct 18 '22 22:10

Yuval Itzchakov


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)
like image 24
grnc Avatar answered Oct 18 '22 22:10

grnc