0

我有以下代码:

private def formatQuery(q:String = ""):String = {
  val q2 = if (q=="") "*" else "'%s'".format(q)
  [...]

我只是想知道是否有一些惯用的方法来避免声明 q2 值

有点像

private def formatQuery(
  q:String = if (q=="") "*" else "'%s'".format(q)
):String = {
  [...]

这显然行不通

4

3 回答 3

4

您是否有特殊原因试图避免分配给变量q2?风格本身似乎很好。

你提出的显然行不通,但这里有两个可行的建议。

如果您的原始功能是:

private def formatQuery(q:String = ""):String = {
  val q2 = if (q=="") "*" else "'%s'".format(q)
  doSomething(q2)
}

一种选择是只在您要传递的地方传递 if-else 表达式q2

private def formatQuery(q:String = ""):String =
  doSomething(if (q=="") "*" else "'%s'".format(q))

另一种是做一个单独的功能:

private def formatQuery(q:String = ""):String =
  runQuery(if (q=="") "*" else "'%s'".format(q))

private def runQuery(q2:String):String =
  doSomething(q2)
于 2012-05-10T05:57:08.223 回答
2

第三种方式是模式匹配。

private def formatQuery(q: String = ""): String = q match {
  case _ if q.length == 0 => "*"
  case _ => "'%s'".format(q)
}

我更喜欢你做的方式,首先是因为它的风格很好。

于 2012-05-10T06:20:31.897 回答
1

Maybe there is a misunderstanding: The val inside of the method body is not a field of the enclosing class or trait or ..., but it is just a local variable. So the keyword val is used for creating fields and for creating local variables.

于 2012-05-10T06:53:23.093 回答