map<A, B, C> function

Either<A, C> Function(Either<A, B> either) map<A, B, C>(
  1. C fn(
    1. B
    )
)

Maps 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 map function to change the inner value of this Either:

final result = map<int, String, int>((s) => s.length)(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 a Left<int>, say Left(404), the output would be:

Error code: 404

@param fn The function to map over 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> either) map<A, B, C>(C Function(B) fn) =>
    match<A, B, Either<A, C>>(
        (left) => Left<A, C>(left), (right) => Right<A, C>(fn(right)));