By Alvin Alexander. Last updated: June 4, 2016
I just ran across this scala-lang.org post about using tuples in an anonymous function, and thought it was good enough to reproduce here, with only the solution part.
In essence, the question is, if I have a Map
like this, which is really composed of tuples:
scala> val x = Map(1 -> "foo", 2 -> "bar") x: scala.collection.immutable.Map[Int,String] = Map(1 -> foo, 2 -> bar)
how do I access each value in each tuple in an anonymous function?
Cutting right to the answer, here’s one way to access all the keys and values in the Map
(which are the tuple components):
scala> x map { case (k,v) => s"$k is $v" } res0: scala.collection.immutable.Iterable[String] = List(1 is foo, 2 is bar)
That’s cool. For related examples that help explain this, see my Iterating over Scala Maps tutorial.
That's all I have for today, but if you want to learn more about tuples, see my Scala tuple examples and syntax tutorial.