map<U> method
If a value is present, returns an Optional describing (as if by ofNullable) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
If the mapping function returns a null result then this method returns an empty Optional.
API Note
This method supports post-processing on Optional values, without the need to explicitly check for a return status. For example, the following code processes a list of names, selects one that starts with 'A', and converts it to uppercase, returning an Optional<String>:
Optional<String> result = names
.where((name) => name.startsWith('A'))
.map(Optional.of)
.firstWhere((opt) => opt.isPresent(), orElse: () => Optional.empty())
.map((name) => name.toUpperCase());
mapper
the mapping function to apply to a value, if present
Returns an Optional describing the result of applying a mapping function to the value of this Optional, if a value is present, otherwise an empty Optional.
Throws InvalidArgumentException if the mapping function is null.
Example
Optional<String> name = Optional.of("henry");
Optional<String> empty = Optional.empty();
// Transform to uppercase
Optional<String> upperName = name.map((s) => s.toUpperCase());
print(upperName.get()); // "HENRY"
// Chain transformations
Optional<int> nameLength = name
.map((s) => s.trim())
.map((s) => s.length);
print(nameLength.get()); // 5
// Empty optionals remain empty
Optional<String> stillEmpty = empty.map((s) => s.toUpperCase());
print(stillEmpty.isEmpty()); // true
// Mapping to null results in empty Optional
Optional<String?> nullResult = name.map((s) => null);
print(nullResult.isEmpty()); // true
// Complex transformations
Optional<Map<String, int>> wordCount = Optional.of("hello world hello")
.map((text) => text.split(' '))
.map((words) {
Map<String, int> count = {};
for (String word in words) {
count[word] = (count[word] ?? 0) + 1;
}
return count;
});
print(wordCount.get()); // {hello: 2, world: 1}
Implementation
Optional<U> map<U>([U? Function(T)? mapper]) {
if (mapper == null) {
throw InvalidArgumentException('mapper cannot be null');
}
if (isEmpty()) {
return empty<U>();
} else {
return Optional.ofNullable(mapper(_value as T));
}
}