0
votes

I have the following code:

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

I'd just like to know if there's some idiomatic way to avoid declaring the q2 value

someting like

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

which obviously doesn't work

3

3 Answers

4
votes

Is there a particular reason you are trying to avoid assigning to a variable q2? The style itself seems fine.

What you proposed obviously doesn't work, but here are two suggestions that would work.

If your original function is:

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

One option is to just pass the if-else expression where you would pass q2:

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

Another is to make a separate function:

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

private def runQuery(q2:String):String =
  doSomething(q2)
2
votes

A third way is pattern matching.

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

I prefer the way you did it, first because it is good style.

1
votes

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.