singleWhereOptional method

Optional<T> singleWhereOptional(
  1. bool test(
    1. T element
    )
)

The single element satisfying test.

Returns Optional.empty() if there are either no elements or more than one element satisfying test.

Notice: This behavior differs from Iterable.singleWhere which always throws if there are more than one match, and only calls the orElse function on zero matchs.

Implementation

Optional<T> singleWhereOptional(bool Function(T element) test) {
  T? result;
  var found = false;
  for (var element in this) {
    if (test(element)) {
      if (!found) {
        result = element;
        found = true;
      } else {
        return Optional.empty();
      }
    }
  }
  return Optional.ofNullable(result);
}