scala / scala-library-next

backwards-binary-compatible Scala standard library additions
Apache License 2.0
69 stars 17 forks source link

Add `option.diff` #178

Open OndrejSpanel opened 7 months ago

OndrejSpanel commented 7 months ago

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 commented 6 months ago

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.