Map

Creates a new Either<TLeft, TRight> value by applying the given mapping functions to either parameter, according to its state.

Parameters

Returns

Func<TRight, TRightResult> mappingWhenRight

Func<TLeft, TLeftResult> mappingWhenLeft

Either<TLeft, TRight> either

Either<TLeftResult, TRightResult>

Usage

This function is usually used to modify an Either value by applying some regular function, just like OptionModule Map.

This function uses the Match method to get the encapsulated value by Either<TLeft, TRight>, then applies the mappingWhenRight or mappingWhenLeft functions, and encapsulate the result.

When Either IsRight

Either<string, int> either = 10;
Either<int, bool> eitherResult = 
    either.Map(
        right => right % 2 == 0,
        left => Convert.ToInt32(left));

//eitherResult.IsRight = true
//eitherResult.Right = true

When Either IsLeft

Either<string, int> either = "25";
Either<int, bool> eitherResult = 
    either.Map(
        right => right % 2 == 0,
        left => Convert.ToInt32(left));

//eitherResult.IsLeft = true
//eitherResult.Left = 25

One sided approach

You can also use the MapLeft and MapRight to produce the same results, but with these methods the mapping is applied just to one of the possible values.

When the target type is different from Either current value the result always will be equals to the either itself.

MapRight when Either IsRight

Either<string, int> either = 10;
Either<string, int> eitherResult = 
    either.MapRight(right => right * 2);

//eitherResult.IsRight = true
//eitherResult.Right = 20

MapRight when Either IsLeft

Either<string, int> either = "Hello World";
Either<string, int> eitherResult = either.MapRight(
right => right * 2);

//eitherResult.IsLeft = true
//eitherResult.Left = "Hello World"

Last updated