I’m developing a simple function that should build a sql condition based on optional parameters that might not be present.
I’m trying to accomplish it using immutables values, and in and elegant and idiomatic way.
So far now I came with something like this:
val cond: Seq[String] = Nil ++
(if (entity != "*") Seq("entity = {entity}") else Nil) ++
(if (name != "*") Seq("name = {name}") else Nil) ++
val condition =
if (cond.size == 0) ""
else " where " + cond.mkString(" and ") + " "
So, I’m just mergins Seqs, if the value is not present I’m merging it with Nil
Working with a var I get something like:
var cond: Seq[String] = Seq();
if (entity != "*") cond = cond :+ "entity = {entity}"
if (name != "*") cond = cond :+ "name = {name}"
Which I find it to be more readable (I wonder if this second approach is not threadsafe because of the var)
I wanted to know what would be a scala idiomatic and elegant way to solve such a thing
— edit
in the end, I settled down with this implementation:
val condition: String = {
var cond: Seq[String] = Seq();
if (entity != "")
cond = cond :+ "entity = {entity}"
if (filter != "")
cond = cond :+ """(name like {filter} or prev like {filter} or post like {filter})"""
if (cond.size == 0) ""
else " where " + cond.mkString(" and ") + " "
}
Another approach is to keep the mutable construction, but hidden in a block to avoid side effects:
Such construct is perfectly safe because the
varis not accessible outside the block. You could also use a val with a mutable builder, for instance aListBuffer. In that case. Just be sure you don’t leak a mutable object out of the block:This is perfectly acceptable because the block itself is still “pure”. This pattern appears in the Scala API.