### Example Usage of toEitherStream (Dart) Source: https://pub.dev/documentation/dart_either/latest/dart_either/ToEitherStreamExtension/toEitherStream Demonstrates how to use the toEitherStream method on a Dart Stream. It shows the conversion of a stream of integers into a stream of Either objects, where each integer is wrapped in an Either.Right. This example highlights the expected output when the source stream emits data events. ```Dart final Stream s = Stream.fromIterable([1, 2, 3, 4]); final Stream> eitherStream = s.toEitherStream((e, s) => e); eitherStream.listen(print); // prints Either.Right(1), Either.Right(2), // Either.Right(3), Either.Right(4), ``` -------------------------------- ### Dart Either.sequence Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/sequence Demonstrates how to use the `sequence` method with different scenarios. It shows short-circuiting with a `Left` and successful collection into a `Right` with a `BuiltList`. ```dart // Result: Left('3') Either.sequence([ 1, 2, 3, 4, 5, 6, ] .map((int i) => i < 3 ? i.toString().right() : i.left())); // Result: Right(BuiltList.of(['1', '2', '3', '4', '5', '6'])) Either.sequence([ 1, 2, 3, 4, 5, 6, ].map((int i) => i.toString().right())); ``` -------------------------------- ### Dart Either catchFutureError Examples Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/catchFutureError Demonstrates various use cases for the catchFutureError method, including handling synchronous exceptions, asynchronous exceptions, successful synchronous futures, and successful asynchronous futures. The examples show how errors are mapped to Left and success values to Right. ```dart // Result: Left(Exception()) await Either.catchFutureError( (e, s) => e, () => throw Exception()) ); // Result: Left(Exception()) await Either.catchFutureError( (e, s) => e, () async => throw Exception()) ); // Result: Right('hoc081098') await Either.catchFutureError( (e, s) => e, () => Future.value('hoc081098')) ); // Result: Right('hoc081098') await Either.catchFutureError( (e, s) => e, () async => await Future.value('hoc081098')) ); ``` -------------------------------- ### Dart Either bimap Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/bimap Demonstrates the usage of the bimap method with a Right value. The rightOperation is applied, transforming the integer to a string. The leftOperation is ignored. ```dart final Either either = Right(1); // Result: Right('1') final Either, String> mapped = either.bimap( leftOperation: (String s) => s.split(''), rightOperation: (int i) => i.toString(), ); ``` -------------------------------- ### Dart Either when Method Usage Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/when Demonstrates how to use the `when` method to conditionally process a Dart `Either` type. It shows how to provide functions for both `ifLeft` and `ifRight` cases and prints output based on the result. This example assumes the existence of `Either`, `Left`, and `Right` classes. ```dart final Either 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}'), ); ``` -------------------------------- ### Dart Either.fromNullable Method Usage Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/fromNullable This example demonstrates how to use the `fromNullable` static method. It shows the resulting Either instance when passing a null value versus a non-null string value. The output clearly illustrates the `Left` and `Right` cases. ```dart Either.fromNullable(null); // Result: Left(null) Either.fromNullable('hoc081098'); // Result: Right('hoc081098') ``` -------------------------------- ### Dart Either.ensure Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/EnsureEitherEffectExtension/ensure Demonstrates the usage of the 'ensure' method within Either.binding. It shows how 'ensure(true)' allows the binding to proceed, while 'ensure(false)' triggers a short-circuit, returning a Left with the value provided by the 'orLeft' callback. ```dart final res = Either.binding((e) { e.ensure(true, () => ''); print('ensure(true) passes'); e.ensure(false, () => 'failed'); return 1; }); // print: 'ensure(true) passes' // res: Left('failed') ``` -------------------------------- ### Dart Either flatMap Method Examples Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/flatMap Demonstrates how the flatMap method works with Dart's Either type. It shows scenarios where flatMap is applied to Right and Left instances, with the provided function returning either a Right or a Left. The examples highlight that flatMap will propagate Left values and execute the function for Right values. ```dart Right(12).flatMap((v) => Right('flower $v')); // Result: Right('flower 12') Right(12).flatMap((v) => Left('flower $v')); // Result: Left('flower 12') Left('12').flatMap((v) => Right('flower $v')); // Result: Left('12') Left('12').flatMap((v) => Left('flower $v')); // Result: Left('12') ``` -------------------------------- ### Either.catchError Constructor Example (Dart) Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/Either.catchError Demonstrates the usage of the Either.catchError constructor. It shows how to handle potential exceptions thrown by a block of code, mapping errors to a Left or successful return values to a Right. This constructor is useful for functional error handling. ```dart Either.catchError((e, s) => e, () => throw Exception()); // Result: Left(Exception()) Either.catchError((e, s) => e, () => 'hoc081098'); // Result: Right('hoc081098') ``` -------------------------------- ### Dart Either foldLeft Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/foldLeft Demonstrates how to use the foldLeft method with an Either.right value. It applies a combining function to an initial string and the Right value, resulting in a folded string. Dependencies: Dart Either package. ```dart final Either result = Either.right('hoc081098'); final String initial = 'dart_either'; String combine(String acc, String v) => '$acc $v'; result.foldLeft(initial, combine); // Result: 'dart_either hoc081098' ``` -------------------------------- ### Dart Either Tap Method Usage Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/tap Demonstrates the usage of the tapLeft method on Dart's Either type. It shows how a function is applied as a side effect to the right value, with the original Either instance being returned regardless of whether the function was executed. This is useful for logging or other non-mutating side effects. ```dart Right(12).tapLeft((_) => print('flower')); // Result: prints 'flower' and returns: Right(12) Left(12).tapLeft((_) => print('flower')); // Result: Left(12) ``` -------------------------------- ### Dart Either bimap Method Example with Left Value Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/bimap Demonstrates the usage of the bimap method with a Left value. The leftOperation is applied, transforming the string into a list of characters. The rightOperation is ignored. ```dart final Either either = Left('hoc081098'); // Result: Left(['h', 'o', 'c', '0', '8', '1', '0', '9', '8']) final Either, String> mapped = either.bimap( leftOperation: (String s) => s.split(''), rightOperation: (int i) => i.toString(), ); ``` -------------------------------- ### Dart Either 'all' Method Usage Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/all Demonstrates how to use the 'all' method with Right and Left instances of Either. The method returns true if the Either is Left, or applies the predicate to the Right value if it's Right. ```dart Right(12).all((v) => v > 10); // Result: true Right(7).all((v) => v > 10); // Result: false Left(12).all((v) => v > 10); // Result: true Left(12).all((v) => v < 10); // Result: true ``` -------------------------------- ### Dart Either tapLeft Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/tapLeft Demonstrates the usage of the tapLeft method on Dart's Either type. It shows how a function is executed only when the Either is a Left, performing a side effect without changing the contained value. The function applied is a fire-and-forget effect. ```dart Right(12).tapLeft((_) => print('flower')); // Result: Right(12) Left(12).tapLeft((_) => print('flower')); // Result: prints 'flower' and returns: Left(12) ``` -------------------------------- ### Dart Either.traverse Example Usage Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/traverse Demonstrates how to use the Either.traverse static method in Dart. It showcases both the short-circuiting behavior when a Left is returned by the mapper and the successful collection of values into a Right. ```dart Either.traverse( [1, 2, 3, 4, 5, 6], (int i) => i < 3 ? i.toString().right() : i.left(), ); Either.traverse( [1, 2, 3, 4, 5, 6], (int i) => i.toString().right(), ); ``` -------------------------------- ### Dart Either fold Method Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/fold Demonstrates how to use the fold method on a Dart Either object. It applies a different function based on whether the Either holds an Exception (Left) or a String (Right), printing a specific message for each case. ```dart final Either result = Either.right('hoc081098'); // Prints operation succeeded with hoc081098 result.fold( ifLeft: (value) => print('operation failed with $value') , ifRight: (value) => print('operation succeeded with $value'), ); ``` -------------------------------- ### Example Usage of ensureNotNull in Dart Either Source: https://pub.dev/documentation/dart_either/latest/dart_either/EnsureNotNullEitherEffectExtension/ensureNotNull Demonstrates how to use the ensureNotNull method within Either.binding. It shows successful non-null checks and how a null value causes short-circuiting with a Left. ```dart final res = Either.binding((e) { int? x = 1; e.ensureNotNull(x, () => 'passes'); print(x); x = null; e.ensureNotNull(x, () => 'failed'); print(x); return 1; }); // println: '1' // res: Left('failed') ``` -------------------------------- ### Dart operator == Implementation Example Source: https://pub.dev/documentation/dart_either/latest/dart_either/Right/operator_equals This snippet shows a typical implementation of the `operator ==` method in Dart. It checks for identity first, then for type compatibility (`Right`) and finally compares the `value` property for equality. This ensures the method adheres to the principles of an equivalence relation. ```dart @override bool operator ==(Object other) => identical(this, other) || (other is Right && value == other.value); ``` -------------------------------- ### Dart Either.futureBinding Implementation Details Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/futureBinding Provides the source code for the `futureBinding` static method. It shows how the method wraps the provided block in a `Future.sync`, handles `ControlError` for early termination, and maps successful results to `Either.right`. ```dart static Future> futureBinding( @monadComprehensions FutureOr Function(EitherEffect effect) block) { final eitherEffect = _EitherEffectImpl(_Token()); return Future.sync(() => block(eitherEffect)) .then((value) => Either.right(value)) .onError>( (e, s) => Either.left(e._value), test: (e) => identical(eitherEffect._token, e._token), ); } ``` -------------------------------- ### Demonstrating Exception Throwing in Dart Source: https://pub.dev/documentation/dart_either/latest/dart_either/index This snippet illustrates functions that throw `UnimplementedError` in Dart. It shows how multiple throwing functions can be composed, highlighting the difficulty in tracking error origins when relying solely on exceptions. ```dart double throwsSomeStuff(int i) => throw UnimplementedError(); String throwsOtherThings(double d) => throw UnimplementedError(); List moreThrowing(String s) => throw UnimplementedError(); List magic(int i) => moreThrowing( throwsOtherThings( throwsSomeStuff(i) ) ); ``` -------------------------------- ### Dart Either.binding Constructor for Monad Comprehensions Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class Demonstrates the use of the `Either.binding` constructor in Dart, which provides syntactic sugar for monad comprehensions (do-notation). This allows monadic pipelines to be written in a more imperative style. ```dart Either.binding(@monadComprehensions R block(EitherEffect effect)) ``` -------------------------------- ### Dart Either.futureBinding for Monadic Comprehensions with Futures Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/futureBinding Demonstrates the usage of `Either.futureBinding` for asynchronous monadic computations. It shows how to use `e.bind` and `e.bindFuture` to sequentially unwrap Eithers and Futures within a `Future>` block. Errors are propagated automatically. ```dart class ExampleError {} Either provideX() { /* ... */ } Future> provideY() { /* ... */ } Future> provideZ(int x, int y) { /* ... */ } Future> result = Either.futureBinding((e) async { int x = provideX().bind(e); // or use `e.bind(provideX())`. int y = await e.bindFuture(provideY()); // or use `await provideY().bind(e)`. int z = await provideZ(x, y).bind(e); // or use `await e.bindFuture(provideZ(x, y))`. return z; }); ``` -------------------------------- ### Either.binding Factory Constructor Implementation in Dart Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/Either.binding Provides the implementation details of the Either.binding factory constructor. It shows how it utilizes EitherEffect and handles ControlError exceptions to manage monadic pipelines. ```dart factory Either.binding( @monadComprehensions R Function(EitherEffect effect) block) { final eitherEffect = _EitherEffectImpl(_Token()); try { return Either.right(block(eitherEffect)); } on ControlError catch (e) { if (identical(eitherEffect._token, e._token)) { return Either.left(e._value); } else { rethrow; } } } ``` -------------------------------- ### ToEitherObjectExtension Methods Source: https://pub.dev/documentation/dart_either/latest/dart_either/ToEitherObjectExtension This section details the methods available on the ToEitherObjectExtension, which allow for the creation of Either objects. ```APIDOC ## ToEitherObjectExtension ### Description Provide left and right extensions on any types. ### Methods #### left() → Either ##### Description Return a Left that contains `this` value. This is a shorthand for `Either.left`. ##### Method Extension Method ##### Parameters None ##### Request Example ```dart final value = 5; final leftEither = value.left(); // Creates Either.left(5) ``` #### right() → Either ##### Description Return a Right that contains `this` value. This is a shorthand for `Either.right`. ##### Method Extension Method ##### Parameters None ##### Request Example ```dart final value = "hello"; final rightEither = value.right(); // Creates Either.right("hello") ``` ``` -------------------------------- ### Dart Either parTraverseN Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/parTraverseN This Dart code implements the `parTraverseN` static method. It takes an iterable of values, a mapper function that returns a `Future>`, and an optional concurrency limit `n`. It leverages `parSequenceN` for parallel execution. The method is marked as experimental. ```dart @experimental static Future>> parTraverseN( Iterable values, Future> Function() Function(T value) mapper, int? n, ) => parSequenceN(values.map(mapper), n); ``` -------------------------------- ### Monadic Operations: Comprehensions and Sequencing Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class Provides syntactic sugar for monadic operations. `futureBinding` offers a do-notation for futures, simplifying chained monadic calls. `sequence` and `traverse` are used for operating on collections of `Either` values, with `sequence` short-circuiting on the first `Left` and `traverse` applying a mapping function. ```dart Future> futureBinding(FutureOr block(EitherEffect effect)) { // Implementation details omitted for brevity throw UnimplementedError(); } Either> sequence(Iterable> values) { // Implementation details omitted for brevity throw UnimplementedError(); } Either> traverse(Iterable values, Either mapper(T value)) { // Implementation details omitted for brevity throw UnimplementedError(); } ``` -------------------------------- ### Left Class Constructor Source: https://pub.dev/documentation/dart_either/latest/dart_either/Left-class Constructs a Left instance with a given value. ```APIDOC ## Left Constructor ### Description Constructs a Left instance with the provided value. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final leftValue = Left("Error occurred"); ``` ### Response #### Success Response (200) None (This is a constructor) #### Response Example None ``` -------------------------------- ### Monadic Comprehension with Either.binding in Dart Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/Either.binding Demonstrates the usage of the Either.binding constructor for monadic comprehensions, akin to do-notation. It shows how to unwrap Right values and propagate Left values within the binding block. ```dart class ExampleError {} Either provideX() { /* ... */ return Either.right(0); } Either provideY() { /* ... */ return Either.right(0); } Either provideZ(int x, int y) { /* ... */ return Either.right(0); } Either result = Either.binding((e) { int x = provideX().bind(e); // or use `e.bind(provideX())`. int y = e.bind(provideY()); // or use `provideY().bind(e)`. int z = provideZ(x, y).bind(e); // or use `e.bind(provideZ(x, y))`. return z; }); ``` -------------------------------- ### Either Methods Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class This section details the available methods for manipulating and querying Either instances. These methods allow for functional-style programming, transforming and handling left (error) and right (success) values. ```APIDOC ## Either Methods ### `all(bool predicate(R value)) → bool` **Description**: Returns `true` if the instance is a Left, or returns the result of applying the given predicate to the Right value. **Method**: Any (Internal to Dart's Either implementation) **Endpoint**: N/A ### `bimap({required C leftOperation(L value), required D rightOperation(R value)}) → Either` **Description**: Maps over both the Left and Right values of this Either instance, applying the respective operations. **Method**: Any **Endpoint**: N/A ### `bind(EitherEffect effect) → R` **Description**: Attempts to get the right value of `this`. Throws a `ControlError` if it's a Left. Available via the `BindEitherExtension`. **Method**: Any **Endpoint**: N/A ### `exists(bool predicate(R value)) → bool` **Description**: Returns `false` if the instance is a Left, or returns the result of applying the given predicate to the Right value. **Method**: Any **Endpoint**: N/A ### `findOrNull(bool predicate(R value)) → R?` **Description**: Returns the Right's value that matches the given predicate, or `null` if this is a Left or the Right's value does not match. **Method**: Any **Endpoint**: N/A ### `flatMap(Either f(R value)) → Either` **Description**: Binds the given function across the Right value. If the instance is Left, it's returned as is. **Method**: Any **Endpoint**: N/A ### `fold({required C ifLeft(L value), required C ifRight(R value)}) → C` **Description**: Applies `ifLeft` if this is a Left, or `ifRight` if this is a Right. This is a way to destructure the Either into a single value. **Method**: Any **Endpoint**: N/A ### `foldLeft(C initial, C rightOperation(C acc, R element)) → C` **Description**: If this is a Right, applies `rightOperation` with the accumulator and the Right's value. Returns `initial` otherwise. **Method**: Any **Endpoint**: N/A ### `getOrElse(R defaultValue()) → R` **Description**: Returns the value from this Right, or the result of `defaultValue()` if this is a Left. **Method**: Any **Endpoint**: N/A ### `getOrHandle(R defaultValue(L value)) → R` **Description**: Returns the value from this Right, or allows clients to transform the Left value into the final result using `defaultValue`. **Method**: Any **Endpoint**: N/A ### `getOrThrow() → R` **Description**: Returns the Right's value if this Either is Right, otherwise throws the Left's value. Equivalent to `getOrHandle((value) => throw value)`. Available via the `GetOrThrowEitherExtension`. **Method**: Any **Endpoint**: N/A ### `handleError(R f(L value)) → Either` **Description**: Handles any error, potentially recovering from it, by mapping the Left value to a new Either instance. **Method**: Any **Endpoint**: N/A ### `handleErrorWith(Either f(L value)) → Either` **Description**: Handles any error by mapping the Left value to a new Either instance with a potentially different Left type. **Method**: Any **Endpoint**: N/A ### `map(C f(R value)) → Either` **Description**: Applies the given function `f` if this is a `Right`. Returns a new Either with the transformed Right value. **Method**: Any **Endpoint**: N/A ### `mapLeft(C f(L value)) → Either` **Description**: Applies the given function `f` if this is a `Left`. Returns a new Either with the transformed Left value. **Method**: Any **Endpoint**: N/A ### `noSuchMethod(Invocation invocation) → dynamic` **Description**: Invoked when a nonexistent method or property is accessed. Inherited from `Object`. **Method**: Any **Endpoint**: N/A ### `orNull() → R?` **Description**: Returns the Right's value if it exists, otherwise returns `null`. **Method**: Any **Endpoint**: N/A ### `redeem({required C leftOperation(L value), required C rightOperation(R value)}) → Either` **Description**: Redeems an Either to a new Either by resolving the Left value or mapping the Right value to a new type C. **Method**: Any **Endpoint**: N/A ### `redeemWith({required Either leftOperation(L value), required Either rightOperation(R value)}) → Either` **Description**: Redeems an Either to a new Either by resolving the Left value or mapping the Right value to a new type C, returning an Either. **Method**: Any **Endpoint**: N/A ### `swap() → Either` **Description**: If this is a `Left`, returns a `Right` containing the Left value. If this is a `Right`, returns a `Left` containing the Right value. **Method**: Any **Endpoint**: N/A ### `tap(void f(R value)) → Either` **Description**: Applies the given function `f` as a side effect if this is a `Right`. The result of `f` is ignored, and the original Either value is returned. **Method**: Any **Endpoint**: N/A ### `tapLeft(void f(L value)) → Either` **Description**: Applies the given function `f` as a side effect if this is a `Left`. The result of `f` is ignored, and the original Either value is returned. **Method**: Any **Endpoint**: N/A ### `toFuture() → Future` **Description**: Converts this Either to a `Future`. If `this` is Right, the Future completes with Right.value. Otherwise, the Future completes with Left.value as its error. Available via the `AsFutureEitherExtension`. **Method**: Any **Endpoint**: N/A ### `toString() → String` **Description**: Returns a string representation of this object. Inherited from `Object`. **Method**: Any **Endpoint**: N/A ### `when({required C ifLeft(Left left), required C ifRight(Right right)}) → C` **Description**: Applies `ifLeft` if this is a Left, or `ifRight` if this is a Right. This method is an alternative to `fold` and is useful for pattern matching. Since Dart 3.0.0, switch expressions can be used instead. **Method**: Any **Endpoint**: N/A ``` -------------------------------- ### Dart Either.right Constructor Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class Demonstrates the creation of a `Right` instance using the `Either.right` constructor. This is used to represent a successful value within the `Either` type. ```dart Either.right(R right) ``` -------------------------------- ### Right Class Properties Source: https://pub.dev/documentation/dart_either/latest/dart_either/Right-class Details about the properties available on the Right class. ```APIDOC ## Right Properties ### Description Provides access to the internal value and state of the Right instance. ### Method GETTER ### Endpoint N/A (Class Properties) ### Parameters None ### Request Example ```dart final rightValue = Right(10); print(rightValue.value); // Output: 10 print(rightValue.isRight); // Output: true print(rightValue.isLeft); // Output: false ``` ### Response #### Success Response (200) - **value** (R) - The actual value contained within the Right instance. - **isLeft** (bool) - Returns `false` as this is a Right instance. - **isRight** (bool) - Returns `true` as this is a Right instance. - **hashCode** (int) - The hash code for this object. - **runtimeType** (Type) - A representation of the runtime type of the object. #### Response Example N/A (Properties are accessed directly on the instance) ``` -------------------------------- ### Right Class Constructor Source: https://pub.dev/documentation/dart_either/latest/dart_either/Right-class Constructs a Right instance with the given value. ```APIDOC ## Right ### Description Represents the right side of a disjoint union. This class is part of the Either type, commonly used for error handling or representing success/failure states. ### Method CONSTRUCTOR ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final rightValue = Right(10); ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Dart Either tapLeft Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/tapLeft Provides the implementation of the tapLeft method for Dart's Either type. This code defines how the tapLeft method operates by conditionally executing a provided function 'f' if the Either instance is a Left, passing the left value to 'f', and always returning the original Either instance. ```dart Either tapLeft(void Function(L value) f) { if (this case Left(value: final value)) { f(value); } return this; } ``` -------------------------------- ### Error Handling with Either.binding and Either.catchError in Dart Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/Either.binding Illustrates the correct way to handle errors within an Either.binding block using Either.catchError. It contrasts the incorrect approach of directly calling a throwing function with the recommended method of catching errors and converting them to Either. ```dart /// This function can throw an error. int canThrowAnError() { /* ... */ return 0; } class ExampleError {} ExampleError toExampleError(Object e, StackTrace st) { /* ... */ return ExampleError(); } // DON'T // Either result = Either.binding((e) { // int value = canThrowAnError(); // }); // DO Either result = Either.binding((e) { int value = Either.catchError( toExampleError, canThrowAnError ).bind(e); return value; }); ``` -------------------------------- ### Dart Either when Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/when Provides the implementation of the `when` method for Dart's `Either` type. This method uses a switch expression to determine whether the current `Either` instance is a `Left` or a `Right` and then calls the corresponding provided function (`ifLeft` or `ifRight`). ```dart C when({ required C Function(Left left) ifLeft, required C Function(Right right) ifRight, }) { final self = this; return switch (self) { Left() => ifLeft(self), Right() => ifRight(self) }; } ``` -------------------------------- ### Dart Either fold Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/fold Shows the internal implementation of the fold method in Dart's Either class. This method takes two required function parameters, `ifLeft` and `ifRight`, and delegates the actual folding logic to an internal method `_foldInternal`. ```dart C fold({ required C Function(L value) ifLeft, required C Function(R value) ifRight, }) => _foldInternal(ifLeft: ifLeft, ifRight: ifRight); ``` -------------------------------- ### Dart Either.futureBinding: Handling Errors with catchError and catchFutureError Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/futureBinding Illustrates how to safely handle errors from synchronous and asynchronous functions within `Either.futureBinding` using `Either.catchError` and `Either.catchFutureError`. These methods convert potential exceptions into Left values, which can then be processed by the monad comprehension. ```dart /// This function can throw an error. int canThrowAnError() { /* ... */ } Future canReturnAnErrorFuture() { /* ... */ } Future errorFuture = Future.error(Exception()); // DON'T // Future> result = Either.futureBinding((e) async { // int value1 = canThrowAnError(); // DON'T // int value2 = await canReturnAnErrorFuture(); // DON'T // int value3 = await errorFuture; // DON'T // return value1 + value2 + value3; // }); // DO ExampleError toExampleError(Object e, StackTrace st) { /* ... */ } Future> result = Either.futureBinding((e) async { int value1 = Either.catchError( toExampleError, canThrowAnError ).bind(e); int value2 = await Either.catchFutureError( toExampleError, canReturnAnErrorFuture ).bind(e); int value3 = await Either.catchFutureError( toExampleError, () => errorFuture ).bind(e); return value1 + value2 + value3; }); ``` -------------------------------- ### Either Methods Source: https://pub.dev/documentation/dart_either/latest/dart_either/Left-class This section details the available methods for the Either data type, covering operations like mapping, folding, error handling, and value retrieval. ```APIDOC ## Either Methods ### all **Description**: Returns `true` if Left or returns the result of the application of the given predicate to the Right value. **Method**: N/A (Instance Method) **Endpoint**: N/A ### bimap **Description**: Map over Left and Right of this Either. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **leftOperation** (Function) - Required - The function to apply to the Left value. - **rightOperation** (Function) - Required - The function to apply to the Right value. ### bind **Description**: Attempt to get right value of `this`. Or throws a ControlError. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **effect** (Function) - Required - The effect to apply. ### exists **Description**: Returns `false` if Left or returns the result of the application of the given `predicate` to the Right value. **Method**: N/A (Instance Method) **Endpoint**: N/A ### findOrNull **Description**: Returns the Right.value matching the given `predicate`, or `null` if this is a Left or Right.value does not match. **Method**: N/A (Instance Method) **Endpoint**: N/A ### flatMap **Description**: Binds the given function across Right. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The function to bind. ### fold **Description**: Applies `ifLeft` if this is a Left or `ifRight` if this is a Right. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **ifLeft** (Function) - Required - The function to apply if Left. - **ifRight** (Function) - Required - The function to apply if Right. ### foldLeft **Description**: If this is a Right, applies `ifRight` with `initial` and Right.value. Returns `initial` otherwise. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **initial** (any) - Required - The initial value. - **rightOperation** (Function) - Required - The function to apply to the Right value. ### getOrElse **Description**: Returns the value from this Right or the given argument if this is a Left. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **defaultValue** (Function) - Required - The default value function. ### getOrHandle **Description**: Returns the value from this Right or allows clients to transform the value of Left to the final result. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **defaultValue** (Function) - Required - The function to handle the Left value. ### getOrThrow **Description**: Returns the Right.value if this Either is Right, otherwise throws the Left.value. **Method**: N/A (Instance Method) **Endpoint**: N/A ### handleError **Description**: Handle any error, potentially recovering from it, by mapping it to an Either value. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The error handling function. ### handleErrorWith **Description**: Handle any error, potentially recovering from it, by mapping it to an Either value. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The error handling function. ### map **Description**: The given function is applied if this is a `Right`. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The mapping function. ### mapLeft **Description**: The given function is applied if this is a `Left`. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The mapping function. ### noSuchMethod **Description**: Invoked when a nonexistent method or property is accessed. **Method**: N/A (Instance Method) **Endpoint**: N/A ### orNull **Description**: Returns the Right's value if it exists, otherwise `null`. **Method**: N/A (Instance Method) **Endpoint**: N/A ### redeem **Description**: Redeem an Either to an Either by resolving the error or mapping the value `R` to `C`. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **leftOperation** (Function) - Required - The operation for the Left value. - **rightOperation** (Function) - Required - The operation for the Right value. ### redeemWith **Description**: Redeem an Either to an Either by resolving the error or mapping the value `R` to `C` with an Either. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **leftOperation** (Function) - Required - The operation for the Left value. - **rightOperation** (Function) - Required - The operation for the Right value. ### swap **Description**: If this is a `Left`, then return the left value in `Right` or vice versa. **Method**: N/A (Instance Method) **Endpoint**: N/A ### tap **Description**: The given function is applied as a fire and forget effect if this is a Right. When applied the result is ignored and the original Either value is returned. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The function to apply. ### tapLeft **Description**: The given function is applied as a fire and forget effect if this is a Left. When applied the result is ignored and the original Either value is returned. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **f** (Function) - Required - The function to apply. ### toFuture **Description**: Convert this Either to a Future. If `this` is Right, the Future will complete with Right.value as its value. Otherwise, the result Future will complete with Left.value as its error. **Method**: N/A (Instance Method) **Endpoint**: N/A ### toString **Description**: A string representation of this object. **Method**: N/A (Instance Method) **Endpoint**: N/A ### when **Description**: Applies `ifLeft` if this is a Left or `ifRight` if this is a Right. **Method**: N/A (Instance Method) **Endpoint**: N/A **Parameters**: #### Request Body - **ifLeft** (Function) - Required - The function to apply if Left. - **ifRight** (Function) - Required - The function to apply if Right. ``` -------------------------------- ### Dart: Monad Comprehensions Constant Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/monadComprehensions-constant This code snippet shows the top-level constant definition for Monad Comprehensions in Dart. It initializes the `_MonadComprehensions` class. ```dart const monadComprehensions = _MonadComprehensions(); ``` -------------------------------- ### Dart Either Tap Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/tap Provides the implementation code for the tap method in Dart's Either type. This method takes a function that accepts the right value and returns void. If the Either instance is a Right, the function is executed; otherwise, it is ignored. The original Either instance is always returned. ```dart Either tap(void Function(R value) f) { if (this case Right(value: final value)) { f(value); } return this; } ``` -------------------------------- ### Dart Either.sequence Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/sequence Provides the implementation of the `sequence` static method for the `Either` class. It iterates through the provided `Iterable` of `Either` values, handling `Left` and `Right` cases. ```dart static Either> sequence(Iterable> values) { final result = ListBuilder(); for (final either in values) { switch (either) { case Left(value: final l): return Either>.left(l); case Right(value: final r): result.add(r); } } return Right(result.build()); } ``` -------------------------------- ### Dart Either.ensure Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/EnsureEitherEffectExtension/ensure Provides the source code implementation for the 'ensure' method. This method checks a boolean condition and, if false, short-circuits the computation by returning a Left using the provided 'orLeft' function. ```dart @monadComprehensions void ensure(bool value, L Function() orLeft) => value ? null : bind(orLeft().left()); ``` -------------------------------- ### Either Operators Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class This section details the operators available for the Dart Either type, primarily focusing on equality comparison. ```APIDOC ## Either Operators ### `operator ==(Object other) → bool` **Description**: The equality operator. Compares this Either instance with another object for equality. Inherited from `Object`. **Method**: Any **Endpoint**: N/A ``` -------------------------------- ### Either Operators Source: https://pub.dev/documentation/dart_either/latest/dart_either/Left-class This section describes the operators available for the Either data type. ```APIDOC ## Operators ### operator == **Description**: The equality operator. **Method**: N/A (Instance Operator) **Endpoint**: N/A **Parameters**: #### Path Parameters - **other** (Object) - Required - The object to compare with. ``` -------------------------------- ### Dart parSequenceN: Concurrent Either Futures Execution Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/parSequenceN The `parSequenceN` method executes a list of functions that return `Future>`. It allows for concurrent execution with a specified limit (`n`) on parallel operations. If any future returns a `Left` value, it's immediately propagated as an error. Otherwise, it collects all `Right` values into a `BuiltList`. ```dart @experimental static Future>> parSequenceN( Iterable> Function()> functions, int? n, ) async { final futureFunctions = functions.toList(growable: false); final semaphore = Semaphore(n ?? futureFunctions.length); final token = _Token(); Future Function() run(Future> Function() f) { return () => Future.sync(f).then( (e) => e.getOrHandle((l) => throw ControlError._(l, token)), ); } Future runWithPermit(Future> Function() f) => semaphore.withPermit(run(f)); return Future.wait( futureFunctions.map(runWithPermit), eagerError: true, ) .then((values) => Either>.right(values.build())) .onError>( (e, s) => Left(e._value), test: (e) => identical(e._token, token), ); } ``` -------------------------------- ### Dart Either.left Constructor Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class Illustrates the creation of a `Left` instance using the `Either.left` constructor. This is used to represent an error value within the `Either` type. ```dart Either.left(L left) ``` -------------------------------- ### Implement toString for Either.Right in Dart Source: https://pub.dev/documentation/dart_either/latest/dart_either/Right/toString This snippet shows the implementation of the toString method for the 'Right' constructor of Dart's Either type. It overrides the default method to provide a developer-friendly string representation of the contained value, primarily for debugging purposes. No external dependencies are required for this method. ```dart @override String toString() => 'Either.Right($value)'; ``` -------------------------------- ### Left Class Properties Source: https://pub.dev/documentation/dart_either/latest/dart_either/Left-class Examines the properties of the Left class, including its value and type information. ```APIDOC ## Left Class Properties ### Description Provides information about the properties available on a Left object. ### Method Property Access ### Endpoint N/A (Instance properties) ### Parameters None ### Request Example ```dart final leftInstance = Left("Some error"); print(leftInstance.value); // Output: Some error print(leftInstance.isLeft); // Output: true print(leftInstance.isRight); // Output: false ``` ### Response #### Success Response (200) - **hashCode** (int) - The hash code for this object. - **isLeft** (bool) - Returns `true` if this is a Left, `false` otherwise. - **isRight** (bool) - Returns `true` if this is a Right, `false` otherwise. - **runtimeType** (Type) - A representation of the runtime type of the object. - **value** (L) - The value inside Left. #### Response Example ```json { "hashCode": 12345, "isLeft": true, "isRight": false, "runtimeType": "Left", "value": "Some error" } ``` ``` -------------------------------- ### Implement Dart Either toString Method for Debugging Source: https://pub.dev/documentation/dart_either/latest/dart_either/ControlError/toString The toString method provides a string representation of the Either object, primarily for debugging or logging. It's useful for classes that don't have a standard textual representation. This implementation shows how to include internal values like _value and _token. ```dart @override String toString() => 'ControlError($_value, $_token)'; ``` -------------------------------- ### Dart Either 'all' Method Implementation Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either/all The internal implementation of the 'all' method for Dart's Either type. It utilizes a fold pattern, returning true for Left and applying the predicate for Right. ```dart bool all(bool Function(R value) predicate) => _foldInternal( ifLeft: _const(true), ifRight: predicate, ); ``` -------------------------------- ### Dart Either.catchError Constructor Source: https://pub.dev/documentation/dart_either/latest/dart_either/Either-class Shows the `Either.catchError` factory constructor in Dart. It evaluates a given block of code and wraps its result in a `Right`, while any errors are mapped using the provided `errorMapper` and returned as a `Left`. ```dart Either.catchError(ErrorMapper errorMapper, R block()) ```