【问题标题】:Scala optimizing optional string parsingScala优化可选字符串解析
【发布时间】:2019-01-24 14:54:47
【问题描述】:

我们需要从一个案例类中创建一个请求查询字符串。案例类包含可选属性:

case class Example(..., str: Option[String], ..)

如果选项存在,我们想创建一个查询参数,否则没有查询参数。喜欢:

match example.str {
  case Some(s) => s"&param_str=$s"
  case _ => ""
}

因为它出现在很多地方,我希望它更通用:

def option2String(optionString: Option[String], template: String) = {
optionString match {
  case Some(str) => template.replaceAll("\\$str", str)
  case _ =>  ""
}

但我认为它可以做得更优雅或 scala 惯用的,可能是call-by-name arguments?

【问题讨论】:

    标签: scala optional stringtemplate


    【解决方案1】:

    我会使用折叠

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

    如果你有多个参数,你可以试试这个:

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

    【讨论】:

    • 谢谢!太糟糕了example.str.fold("")(s"&param_str=$_") 是不允许的。
    • 不允许?您也可以使用 map / getOrElse 组合。
    • example.str.fold("")(s => s"&param_str=$s") 删除字符串 concat
    • @drjerry 我选择了那个特定版本,因为我认为它看起来最干净,而且可能是最有效的,但其他变体当然也是可能的。
    猜你喜欢
    • 2015-03-31
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2015-10-03
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多