Reputation: 24821
Very handy Ruby code:
some_map.each do |key,value|
# do something with key or value
end
Scala equivalent:
someMap.foreach( entry => {
val (key,value) = entry
// do something with key or value
})
Having to add the extra val
line bugs me. I couldn't figure out how to state the function arg to extract the tuple, so I'm wondering is there a way to do this, or why is there no foreach that extracts the key and value for me?
Upvotes: 11
Views: 1401
Reputation: 26579
I like this one:
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
Upvotes: 11
Reputation: 33092
Function.tupled converts a function (a1, a2) => b)
to a function ((a1, a2)) => b
.
import Function._
someMap foreach tupled((key, value) => printf("%s ==> %s\n", key, value))
Upvotes: 2
Reputation: 11292
You don't need even the val
in for loop:
Following ViktorKlang's example:
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
Note that for
is rather powerful in Scala, so you can also use it for sequence comprehensions:
scala> val bar = for (val (k, v) <- foo) yield k
bar: Iterable[Int] = ArrayBuffer(1, 2)
Upvotes: 5
Reputation: 370102
This works, too:
someMap.foreach {case (key, value) =>
// do something with key and/or value
}
Upvotes: 19