0

我已经做了足够多的 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 没有“过滤器”方法(它认为我们正在在线过滤(k,v) <- m)谢谢!

4

2 回答 2

4

接受选项是可迭代的事实

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

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

无抗性

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 = ""
于 2016-11-08T21:58:26.403 回答
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(", ")
于 2016-11-09T06:30:38.247 回答