Search code examples
scalaoption-typestringtemplate

Scala optimizing optional string parsing


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"&param_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?


Solution

  • I would use fold

    example.str.fold("")("&param_str=" + _)
    

    If you have multiple parameters you can try this:

    List(
      str1.map("&param1_str=" + _),
      str2.map("&param2_str=" + _),
      str3.map("&param3_str=" + _)
    ).flatten.mkString(" ")