scala, filter a collection based on several conditions

scala

Solution

You could use an implicit class to give you this syntax:

  val strs = List("hello", "andorra", "trab", "world")

  def f1(s: String) = !s.startsWith("a")

  def f2(s: String) = !s.endsWith("b")

  val cond1 = true
  val cond2 = true

  implicit class FilterHelper[A](l: List[A]) {
    def ifFilter(cond: Boolean, f: A => Boolean) = {
      if (cond) l.filter(f) else l
    }
  }

  strs
    .ifFilter(cond1, f1)
    .ifFilter(cond2, f2)

res1: List[String] = List(hello, world)

I would have used `if` as the method name but it's a reserved word.

Problem

I have a code such as: ``` val strs = List("hello", "andorra", "trab", "world") def f1(s: String) = !s.startsWith("a") def f2(s: String) = !s.endsWith("b") val result = strs.filter(f1).filter(f2) ``` now, f1 and f2 should be applied based on a condition, such as: ``` val tmp1 = if (cond1) strs.filter(f1) else strs val out = if (cond2) tmp1.filter(f2) else tmp1 ``` is there a nicer way to do this, without using a temporary variable `tmp1`? one way would to filter based on a list of functions, such as: ``` val fs = List(f1 _,f2 _) fs.foldLeft(strs)((fn, list) => list.filter(fn)) ``` but then I would need to build a list of functions based on the conditions (and so, I would move the problem of using a temporary string list variable, to using a temporary function list variable (or I should need to use a mutable list)). I am looking something like this (of course this does not compile, otherwise I would already have the answer to the question): ``` val result = strs .if(cond1, filter(f1)) .if(cond2, filter(f2)) ```

Original source