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?
This works, too:
someMap.foreach {case (key, value) =>
// do something with key and/or value
}
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With