我有这样的def:
def formatMap(sep: String = ": ",
left: String = "{", right: String = "}")(m: Map[String, String]) = {
val items = m.toSeq.map{case (k, v) => {
if( k contains "region") {
s"$k$sep'$v'"
} else {
s"$k$sep$v"
}
}}.mkString(", ")
s"$left$items$right"
}
但我需要将其转换为一个案例来查看多个规则,我尝试这样做:
def formatMap(sep: String = ": ",
left: String = "{", right: String = "}")(m: Map[String, String]) = {
val items = m.toSeq.map{case (k, v) => {
def val2($k: Any): Any = $k match {
case "region" | "popn_typ_cd" | "prod_type_cd" | "ent_prod_cd" => s"$k$sep'$v'"
case _ => s"$k$sep$v"
}
}}.mkString(", ")
s"$left$items$right"
}
第二种情况只是给了我空白值...它似乎没有输出s"$k$sep'$v'"
或"$k$sep$v"
是我的案例陈述设置相关吗?
编辑:
我让它像这样工作:
def formatMap(sep: String = ": ",
left: String = "{", right: String = "}")(m: Map[String, String]) = {
val items = m.toSeq.map{case (k, v) => {
if( k contains "region") {s"$k$sep'$v'"} else {
if( k contains "popn_typ_cd") {s"$k$sep'$v'"} else {
if( k contains "prod_type_cd") {s"$k$sep'$v'"} else {
if( k contains "ent_prod_cd") {s"$k$sep'$v'"} else {s"$k$sep$v"}}}}
}}.mkString(", ")
s"$left$items$right"
}
但我仍然想知道如何通过案例陈述......
答案 0 :(得分:1)
问题在于def val2
版本中的formatMap
:
def formatMap(sep: String = ": ",
left: String = "{", right: String = "}")(m: Map[String, String]) = {
val items = m.toSeq.map{case (k, v) => {
def val2($k: Any): Any = $k match {
case "region" | "popn_typ_cd" | "prod_type_cd" | "ent_prod_cd" => s"$k$sep'$v'"
case _ => s"$k$sep$v"
}
}}.mkString(", ")
s"$left$items$right"
}
你正在创建一个函数,但你永远不会调用它。你可以
在val2(k)
之前插入}}.mkString(", ")
并使用$$k
代替$k
,因为您的参数称为$k
,或者甚至更好,您可以避免
def
并写:
def formatMap(sep: String = ": ",
left: String = "{", right: String = "}")(m: Map[String, String]) = {
val items = m.toSeq.map { case (k, v) =>
k match {
case "region" | "popn_typ_cd" | "prod_type_cd" | "ent_prod_cd" => s"$k$sep'$v'"
case _ => s"$k$sep$v"
}}.mkString(", ")
s"$left$items$right"
}
行动中:
scala> formatMap()(Map("one" -> "eins", "two" -> "zwei", "region" -> "EU"))
res1: String = "{one: eins, two: zwei, region: 'EU'}"