when<C> method
Applies ifLeft
if this is a Left or ifRight
if this is a Right.
This is quite similar to fold, but with fold, arguments will be called with Right.value or Left.value, while the arguments of when will be called with Right or Left itself.
ifLeft
is the function to apply if this is a Left.
ifRight
is the function to apply if this is a Right.
Returns the results of applying the function.
Example
final Either<String, int> result = Right(1);
// Prints operation succeeded with 1
result.when(
ifLeft: (left) => print('operation failed with ${left.value}') ,
ifRight: (right) => print('operation succeeded with ${right.value}'),
);
Implementation
C when<C>({
required C Function(Left<L, R> left) ifLeft,
required C Function(Right<L, R> right) ifRight,
}) {
if (isLeft) {
return ifLeft(this as Left<L, R>);
} else {
assert(isRight);
return ifRight(this as Right<L, R>);
}
}