Quite a few functions on Map
take a function on a key-value tuple as the argument. E.g. def foreach(f: ((A, B)) ⇒ Unit): Unit
. So I looked for a short way to write an argument to foreach
:
> val map = Map(1 -> 2, 3 -> 4)
map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)
> map.foreach((k, v) => println(k))
error: wrong number of parameters; expected = 1
map.foreach((k, v) => println(k))
^
> map.foreach({(k, v) => println(k)})
error: wrong number of parameters; expected = 1
map.foreach({(k, v) => println(k)})
^
> map.foreach(case (k, v) => println(k))
error: illegal start of simple expression
map.foreach(case (k, v) => println(k))
^
I can do
> map.foreach(_ match {case (k, v) => println(k)})
1
3
Any better alternatives?
You were very close with map.foreach(case (k, v) => println(k))
. To use case
in an anonymous function, surround it by curly brackets.
map foreach { case (k, v) => println(k) }
In such cases I often use the for
syntax.
for ((k,v) <- map) println(k)
According to Chapter 23 in "Programming in Scala" the above for loop is translated to call foreach
.
One alternative is the tupled
method of the Function
object:
import Function.tupled;
// map tupled foreach {(k, v) => println(k)}
map foreach tupled {(k, v) => println(k)}
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