0

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!

dlite922
  • 1,924
  • 3
  • 24
  • 60

2 Answers2

4

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 = ""
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
  • 2
    good answer, but I think it's better you avoid "map" as name because it may lead to confusion. – Chosmos Nov 08 '16 at 22:03
0
scala> val sm: Option[Map[String,String]] = Some(Map("Foo" -> "won", "Bar" -> "too", "Baz" -> "tree"))
sm: Option[Map[String,String]] = Some(Map(Foo -> won, Bar -> too, Baz -> tree))

scala> val yourString = sm.getOrElse(Map[String, String]()).toList.map({
  case (key, value) => s"$key=$value"
}).mkString(", ")
sarveshseri
  • 13,738
  • 28
  • 47