如何在 Scala 中打开 Option[Map(A,B)]?

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

我对 Scala 的了解已经够多了,知道丑陋的代码是什么样子的。观察:

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

预期输出:

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

这是我的 Tyler Perry 代码,由 M. Knight Shama Llama Yama 执导:

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

然而,当 sm 为 None 时,这不起作用 :-( 。我收到一条错误消息,指出 Nothing 没有 "filter" 方法(它认为我们正在过滤行 (k,v) <- m) 谢谢!

接受选项是可迭代的事实

(for {
   map <- sm.iterator
   (k, v) <- map.iterator
  } yield s"$k=$v").mkString(",")

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

None耐

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