Reputation: 3337
I have a def like this:
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"
}
but I need to convert it to a case to look at multiple rules and I tried to do this:
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"
}
The second case just gives me back blank values...it doesn't seem to be outputting the s"$k$sep'$v'"
or "$k$sep$v"
is my case statement setup correclty?
EDIT:
I got it to work like this:
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"
}
but I would still like to know how to do it via the case statement...
Upvotes: 1
Views: 235
Reputation: 2869
The problem is the def val2
in your version of 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"
}
you are creating a function, but you never call it. Either you can
insert val2(k)
before }}.mkString(", ")
and use $$k
instead of $k
because your argument is called $k
or even better you can just avoid
the def
and write:
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"
}
In action:
scala> formatMap()(Map("one" -> "eins", "two" -> "zwei", "region" -> "EU"))
res1: String = "{one: eins, two: zwei, region: 'EU'}"
Upvotes: 1