Scala - Using tuples in an anonymous function

I just ran across this 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.

This website is a little one-man operation. If you found this information helpful, I’d appreciate it if you would share it.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.