Scala:迭代时提取元组值

Cli*_*ote 0 dictionary functional-programming scala pattern-matching scala-collections

假设我有这张地图: Map[String, Int]

为了迭代它的值,我必须这样做:

myMap.foreach(t => {
    val word = t._1
    val number = t._2
    //do stuff with word and number here
})
Run Code Online (Sandbox Code Playgroud)

有没有办法做这样的事情:

myMap.foreach( (word, number) => {
    //do stuff with word and number here
})
Run Code Online (Sandbox Code Playgroud)

使用 Scala 2.13.2 atm

And*_*cus 5

您可以使用模式匹配:

myMap.foreach { case (word, number) => ... }
Run Code Online (Sandbox Code Playgroud)

或用于:

for((word, number) <- myMap) {
  ...
}
Run Code Online (Sandbox Code Playgroud)