简体   繁体   中英

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?

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(" ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM