foreach loop in scala

Viewed 47815

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.

4 Answers

Vector is working a bit differently, you using function literals using case...

In Scala, we using brackets{} which accept case...

{
  case pattern1 => "xxx"
  case pattern2 => "yyy"
}

So, in this case, we using it with foreach loop...

Print all values using the below pattern then:

val nums = Vector((1,9), (2,8), (3,7), (4,6), (5,5))

nums.foreach {
    case(key, value) => println(s"key: $key, value: $value")
}

Also you can check other loops like for loop as well if you think this is not something which you are comfortable with...

Related