filter method
If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.
predicate
the predicate to apply to a value, if present
Returns an Optional describing the value of this Optional, if a value is present and the value matches the given predicate, otherwise an empty Optional.
Throws InvalidArgumentException if the predicate is null.
Example
Optional<String> name = Optional.of("Grace");
Optional<String> empty = Optional.empty();
// Filter based on length
Optional<String> longName = name.filter((s) => s.length > 3);
print(longName.isPresent()); // true (Grace has 5 characters)
Optional<String> shortName = name.filter((s) => s.length < 3);
print(shortName.isEmpty()); // true (Grace is not less than 3 characters)
// Empty optionals remain empty after filtering
Optional<String> stillEmpty = empty.filter((s) => s.isNotEmpty);
print(stillEmpty.isEmpty()); // true
// Chain with other operations
Optional<String> result = Optional.of("hello world")
.filter((s) => s.contains("world"))
.map((s) => s.toUpperCase());
print(result.get()); // "HELLO WORLD"
Implementation
Optional<T> filter([bool Function(T)? predicate]) {
if (predicate == null) {
throw InvalidArgumentException('predicate cannot be null');
}
if (isEmpty()) {
return this;
} else {
return predicate(_value as T) ? this : empty<T>();
}
}