tags:

views:

272

answers:

4

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?

+12  A: 

This works, too:

someMap.foreach {case (key, value) =>
  // do something with key and/or value
}
sepp2k
+6  A: 

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
Viktor Klang
There's no need for `val` inside the `for` generator.
Daniel
+4  A: 

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)
andri
`for` is actually a Monad Comprehension disguised as a `for` loop, so as to not scare away the Java programmers with concepts such as *Monad*. (Just like query comprehensions in C#/VB.NET are just monad comprehensions disguised as SQL queries.) So, it's even more powerful than sequence comprehensions.
Jörg W Mittag
Jörg, don't use the M word, it scares people ;-)
Viktor Klang
@ViktorKlang: Exactly! That's why Martin Odersky disguised them as something Java programmers already know: a `for` loop. And Erik Meijer disguised them as a SQL query in C# and VB.NET, Don Syme disguised them as a Unix shell pipeline in F#, Simon Peyton Jones disguised them as a C block in Haskell. (Sometimes I think they would be *less* scary if they weren't constantly hiding in the shadows ...)
Jörg W Mittag
+2  A: 

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))
Thomas Jung