flatMap<A, B, C> function
- Either<
A, C> fn(- B
FlatMaps over the Either type.
Transforms an Either<A, B> into an Either<A, C> by applying the given function fn to the inner value if it's of type Right<B>.
If the Either is a Left<A>, it returns the same Left<A> without any modification.
Example:
Consider you have an Either that can be an integer error code or a valid string:
Either<int, String> name = Right("Alice");
You can use the flatMap function to derive another Either based on this value:
final result = flatMap<int, String, int>((s) => s == "Alice" ? Right(s.length) : Left(-1))(name);
if (result is Right<int>) {
print("Name length is ${result.value}");
} else if (result is Left<int>) {
print("Error code: ${result.value}");
}
In this example, since name is Right("Alice"), the output will be:
Name length is 5
If name was any other Right<String> value, the output would be:
Error code: -1
If name was a Left<int>, say Left(404), the output would be:
Error code: 404
@param fn The function to apply on the inner value.
@return A function that takes in an Either<A, B> and returns an Either<A, C>.
Implementation
Either<A, C> Function(Either<A, B>) flatMap<A, B, C>(
Either<A, C> Function(B) fn) =>
match<A, B, Either<A, C>>((a) => Left<A, C>(a), fn);