简体   繁体   English

Scala优化可选的字符串解析

[英]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? 但是我认为这可以更优雅或更简单地使用scala 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(" ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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