Search code examples
scaladictionaryfor-comprehensionflatmapscala-option

How to open an Option[Map(A,B)] in Scala?


I've done enough Scala to know what ugly code looks like. Observe:

 val sm Option[Map[String,String]] = Some(Map("Foo" -> "won", "Bar" -> "too", "Baz" -> "tree"))

Expected output:

 : String = Foo=won,Bar=too,Baz=tree

Here's my Tyler Perry code directed by M. Knight Shama Llama Yama:

 val result = (
     for { 
         m <- sm.toSeq; 
         (k,v) <- m
     } yield s"$k=$v"
 ).mkString(",")

However this does not work when sm is None :-( . I get an error saying that Nothing has no "filter" method (it thinks we're filtering on line (k,v) <- m) Gracias!


Solution

  • Embrace the fact that option is iterable

    (for {
       map <- sm.iterator
       (k, v) <- map.iterator
      } yield s"$k=$v").mkString(",")
    
    res1: String = "Foo=won,Bar=too,Baz=tree"
    

    None resistant

    scala> val sm: Option[Map[String, String]] = None
    sm: Option[Map[String, String]] = None
    
    scala> (for {
       map <- sm.iterator
       (k, v) <- map.iterator
      } yield s"$k=$v").mkString(",")
    res44: String = ""