Scala相当于Ruby的map.each?

时间:2010-02-06 21:52:21

标签: scala

非常方便的Ruby代码:

some_map.each do |key,value|
  # do something with key or value
end

Scala等价物:

someMap.foreach( entry => {
  val (key,value) = entry
  // do something with key or value
})

我必须添加额外的val行。我无法弄清楚如何声明函数arg来提取元组,所以我想知道有没有办法做到这一点,或者为什么没有foreach为我提取关键和值?

4 个答案:

答案 0 :(得分:19)

这也有效:

someMap.foreach {case (key, value) =>
  // do something with key and/or value
}

答案 1 :(得分:11)

我喜欢这个:

scala> val foo = Map( 1 -> "goo", 2 -> "boo" )
foo: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> goo, 2 -> boo)

scala> for ((k,v) <- foo) println(k + " " + v)
1 goo
2 boo

答案 2 :(得分:5)

你甚至不需要val for for循环:

关注ViktorKlang的例子:

scala> val foo = Map( 1 -> "goo", 2 -> "boo" )
foo: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> goo, 2 -> boo)

scala> for ((k, v) <- foo) println(k + " " + v)
1 goo
2 boo

请注意,for在Scala中相当强大,因此您也可以将其用于sequence comprehensions

scala> val bar = for (val (k, v) <- foo) yield k
bar: Iterable[Int] = ArrayBuffer(1, 2)

答案 3 :(得分:2)

Function.tupled将函数(a1, a2) => b)转换为函数((a1, a2)) => b

import Function._
someMap foreach tupled((key, value) => printf("%s ==> %s\n", key, value))