We need to create an request query-string, from a case class. The case class contains optional attributes:
case class Example(..., str: Option[String], ..)
We want to create a query-parameter if the option exists, and no query parameter otherwise. Like:
match example.str {
case Some(s) => s"¶m_str=$s"
case _ => ""
}
as this appearing at numerous places I want it to make a bit more generic:
def option2String(optionString: Option[String], template: String) = {
optionString match {
case Some(str) => template.replaceAll("\\$str", str)
case _ => ""
}
But I think it can be done more elegant or scala idiomatic, may be with call-by-name arguments?
I would use fold
example.str.fold("")("¶m_str=" + _)
If you have multiple parameters you can try this:
List(
str1.map("¶m1_str=" + _),
str2.map("¶m2_str=" + _),
str3.map("¶m3_str=" + _)
).flatten.mkString(" ")