我已经做了足够的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时,这不起作用:-(。我得到一个错误,说没有什么没有&#34;过滤&#34;方法(它认为我们在线(k,v) <- m
上进行过滤格拉西亚斯!
答案 0 :(得分:3)
(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 = ""
答案 1 :(得分: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(", ")