简体   繁体   中英

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!

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 = ""
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(", ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM