dlite922 dlite922 - 23 days ago 13
Scala Question

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!

Answer

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 = ""
Comments