Suppose I have an Option[A => Boolean], a List[A], and some set of operations I want to perform on a subset of that list. If the option is set, then I want to filter the list first and then apply my operations. If not, then I want to apply it on the whole list. An example:
val a : Option[Int => Boolean] = Option((a : Int) => a % 2 == 0)
val b = 1 to 100
I can easily do the following:
val c = if (a.isDefined) b.filter(a.get) else b
However, this involves calling a.get; much conditioning leaves me unable to do this! I could alternatively do:
val c = b.filter(a.getOrElse(_ => true))
This feels better, but now I am stuck with a second (albeit trivial) operation being carried out for every element of my sequence. I could hope that it will be optimised out, but this still feels imperfect.
What I would like is something lacking either flaw. It feels like there should be a nice way to do it – any ideas?
You just need to use the normal option handling methods: