Using builder-like functions conditionally

Viewed 140

Assume this situation:

I have a Tuple of size n. Each element is a Boolean flag that defines if a specific function should be called on an object (here: builder).

The syntax that comes to my mind first would be:

(el1, el2, el3, ...) => {
   val builder = MyBuilder()

   val builder1 = if(el1) builder.func1(...) else builder
   val builder2 = if(el2) builder1.func2(...) else builder1
   val builder3 = if(el3) builder2.func3(...) else builder2
   ...
}

The last builder builderN would be the desired object. But this code is nasty.

What would be a good, clean alternative? (Note: I am using cats.)

Another way to represent my problem would be:

val result = MyBuilder.
   .func1(...) //ONLY if el1!
   .func2(...) //ONLY if el2!
   .func3(...) //ONLY if el3!
   ....
   .funcn(...) //ONLY if el4!

EDIT : Fixed example code!

1 Answers

You can zip list of flags with list of building functions and then in the fold conditionally apply builder function

class Builder() {

  def func1(in: Any): Builder = {
    println("func1")
    this
  }

  def func2(in: Any): Builder = {
    println("func2")
    this
  }

  def func3(in: Any): Builder = {
    println("func3")
    this
  }
}

val flags = List(true, false, true)
val funcs = List[Builder => Builder](b => b.func1(1), b => b.func2(2), b => b.func3(3))
val result = flags.zip(funcs).foldLeft(new Builder()) {
  case (builder, (flag, func)) => if (flag) func(builder) else builder
}

prints to console:

func1
func3
Related