Either<L, R> class
abstract
A generic type that represents a value of one of two possible types (a disjoint union).
Instances of Either are either an instance of Left or Right.
- Left is used to represent failure, typically holding an error or exception.
- Right is used to represent success, typically holding a valid result.
Either<L, R> is commonly used as a functional alternative to throwing exceptions.
Example:
void main() {
final result1 = divide(10, 2);
final result2 = divide(5, 0);
result1.fold(
(error) => print('Error: $error'),
(value) => print('Result: $value'),
); // Prints: Result: 5
result2.fold(
(error) => print('Error: $error'),
(value) => print('Result: $value'),
); // Prints: Error: Cannot divide by zero
// Using map
final mappedResult = result1.map((value) => value * 2);
print(mappedResult.getRight()); // Prints: 10
}
Either<String, int> divide(int a, int b) {
if (b == 0) {
return const Left('Cannot divide by zero');
} else {
return Right(a ~/ b);
}
}
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
flatMap<
R2> (Either< L, R2> f(R right)) → Either<L, R2> -
Applies the function
fto the value contained in Right, if it exists, and returns a new Either containing the result. If this is a Left, it is returned unchanged. -
fold<
B> (B ifLeft(L left), B ifRight(R right)) → B - Applies one of two functions depending on whether this is a Left or Right.
-
getLeft(
) → L - Returns the Left value if this is a Left, otherwise throws.
-
getRight(
) → R - Returns the Right value if this is a Right, otherwise throws.
-
isLeft(
) → bool -
Returns
trueif this is a Left. -
isRight(
) → bool -
Returns
trueif this is a Right. -
map<
R2> (R2 f(R right)) → Either< L, R2> -
Transforms the value contained in Right using the given function
f, returning a new Either with the transformed value. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited