scala-library-next icon indicating copy to clipboard operation
scala-library-next copied to clipboard

Add `option.diff`

Open OndrejSpanel opened this issue 1 year ago • 1 comments

Add diff to Option for a symmetry with Seq. Reference implementation:

  implicit class OptionValueOps[T](private val o: Option[T]) extends AnyVal {
    final def diff(that: Option[T]): Option[T] = {
      if (that.exists(o.contains)) None
      else o
    }
  }

OndrejSpanel avatar Apr 19 '24 17:04 OndrejSpanel

It can be even made a little bit more general:

implicit class OptionValueOps[T](private val o: Option[T]) extends AnyVal {
  final def diff(that: Iterable[T]): Option[T] = {
    if (o.exists(that.contains)) None
    else o
  }
}

Note: o.exists(that.contains) should be more performant than that.exists(o.contains) when that.contains is more efficient than that.exists, e.g. for Set.

OndrejSpanel avatar May 22 '24 00:05 OndrejSpanel