Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 370
Ralph Avatar asked Dec 10 '22 00:12

Ralph


2 Answers

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) _)
like image 193
Travis Brown Avatar answered Dec 29 '22 06:12

Travis Brown


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
like image 43
Luigi Plinge Avatar answered Dec 29 '22 08:12

Luigi Plinge