scalafilteringscala-option

Filtering on Scala Option[Set]


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.


Solution

  • 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) _)