Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent of Ruby's map.each?

Tags:

scala

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?

like image 389
davetron5000 Avatar asked Feb 06 '10 21:02

davetron5000


3 Answers

This works, too:

someMap.foreach {case (key, value) =>
  // do something with key and/or value
}
like image 175
sepp2k Avatar answered Nov 01 '22 06:11

sepp2k


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
like image 42
Viktor Klang Avatar answered Nov 01 '22 05:11

Viktor Klang


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)
like image 35
andri Avatar answered Nov 01 '22 07:11

andri