I have a Scala value of type Option[Set[String]] that I am trying to use in a collection filter method:
val opt: Option[Set[String]] = ...
collection.filter {
  value =>
  opt match {
    case Some(set) => set.contains(value)
    case None => true
  }
}
If the opt value is Some(...) I want to use the enclosed Set to filter the collection, otherwise I want to include all items in the collection.
Is there a better (more idiomatic) way to use the Option (map, filter, getOrElse, etc.)?
The opt comes from an optional command line argument containing a list of terms to include. If the command line argument is missing, then include all terms.
I'd use the fact that Set[A] extends A => Boolean and pass the constant function returning true to getOrElse:
val p: String => Boolean = opt.getOrElse(_ => true)
Or:
val p = opt.getOrElse(Function.const(true) _)
Now you can just write collection.filter(p). If you want a one-liner, either of the following will work as well:
collection filter opt.getOrElse(_ => true)
collection filter opt.getOrElse(Function.const(true) _)
                        It seems a bit wasteful to filter on _ => true so I would prefer
opt match {
  case Some(s) => collection filter s
  case None    => collection
}
I guess this equates to:
opt map (collection filter) getOrElse collection
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With