[英]foreach loop in scala
In scala foreach loop if I have list 在scala foreach循环中,如果我有列表
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. 请解释执行两个foreach循环时会发生什么。
You don't have to, you choose to. 您没有,您选择。 The problem is that the current Scala compiler doesn't deconstruct tuples, you can do: 问题是当前的Scala编译器没有解构元组,你可以这样做:
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: 这就是编译器在你使用case
时所做的事情:
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. 您会看到它在未命名的x0$1
上匹配模式,并将_1
和_2
分别放在i
和j
。
According to http://alvinalexander.com/scala/iterating-scala-lists-foreach-for-comprehension : 根据http://alvinalexander.com/scala/iterating-scala-lists-foreach-for-comprehension :
val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
for (name <- names)
println(name)
Vector is working a bit differently, you using function literals using case... Vector的工作方式有点不同,你使用case使用函数文字...
In Scala, we using brackets {}
which accept case
... 在Scala中,我们使用括号{}
来接受case
......
{
case pattern1 => "xxx"
case pattern2 => "yyy"
}
So, in this case, we using it with foreach loop... 所以,在这种情况下,我们将它与foreach循环一起使用......
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... 你也可以检查其他循环,比如for循环,如果你认为这不是你觉得舒服的东西......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.