scala Scala中的foreach循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45165065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
foreach loop in scala
提问by Srinivas
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) }
- a pattern matching case
- { brackets
- 模式匹配案例
- { 括号
Please explain what happens when the two foreach loops are executed.
请解释执行两个 foreach 循环时会发生什么。
采纳答案by Yuval Itzchakov
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 caselike 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: (Int, Int)) => x0 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$1and puts _1and _2inside iand j, respectively.
您会看到它分别在未命名x0$1和 puts_1以及_2insidei和上进行模式匹配j。
回答by grnc
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)
回答by Patrick Junger
回答by Alireza
Vectoris working a bit differently, you using function literals using case...
Vector的工作方式略有不同,您使用大小写的函数文字...
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 循环......

