Map Over the Keys/Values from an Option

I am trying to extract they keys/values from an Option[Map]. What is the simplest way to iterate over the key/values contains in the Map, only if the Option actually has a Map?

Here is a simple example that highlights my problem.

val values = Option(Map("foo" -> 22, "bar" -> 23))
values map { case (key, value) => println(s"$key = $value") }  

This fails to compile.

 <console>:12: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: scala.collection.immutable.Map[String,Int]
              values map { case (key, value) => println(s"$key = $value") }
                                ^

If the Map is not wrapped in an Option, then it works just fine.

val values = Map("foo" -> 22, "bar" -> 23)
values map { case (key, value) => println(s"$key = $value") }

Answers


You need another map, because the first map is for the Option, which means the your lambda is trying to match a single key-value pair, when it's really the full Map contained in the Option.

values.map(a => ???)
           ^ This is a Map[String, Int]

Syntactically, you want this:

values.map(_.map { case (key, value) => println(s"$key = $value") })

But this isn't really a map in it's true sense, it's more like a foreach since it only produces a side-effect.

values.foreach(_.foreach { case (key, value) => println(s"$key = $value") })

Or with a for-comprehension:

for {
    map <- values
    (key, value) <- map
} println(s"$key = $value")

Need Your Help

Eclipse : change permission file and commit does not work

eclipse svn

I just forget to applied permission of the files that I just recently commited, but when afterwards I add permission to those file (chmod 755), eclipse can not detect the changes commit it again

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.