hasanmhallak/Either

isRight is missing

Closed this issue · 3 comments

Please add a bool get isRight method. It is cleaner and less read error prone than using !item.isLeft.

Hi @bwhiteFC, it was not my intention to expose isLeft in the first place because this library should be more of functional style. and I could not think of any use case where isLest or isRight would be useful.

You can simply check if the instance is a Left or Right by using the is operator like this:

  final data = right<String, int>(45);

  final isRight = data is Right;

  print(isRight); // true

or you can simply use the function style like this:

  Either<String, int> foo() {
    // some work here

    return left('result');
  }

  final result = foo();

// you can use call backs like this:
  result.fold(
    (left) => print(left), // this call back will run and prints "result"
    (right) => print('failure'),
  );

// or you can cast it like this
  final isLeft = result is Left;
  print(isLeft); // true

If you have a specific use case that requires the isRight method, just let me know and I'll happily add it.

It is useful for validation. Example:

abstract class ValueObject<T> {
  const ValueObject();

  Either<ValueFailure<T>, T> get value;

  T getOrThrow() {
    return value.fold(
      (left) => throw UnexpectedValue(value: left),
      (right) => right,
    );
  }

  T getOrElse(T other) {
    return value.fold((left) => other, (right) => right);
  }

  bool isValid() => value.isRight();

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is ValueObject<T> && other.value == value;
  }

  @override
  int get hashCode => value.hashCode;

  @override
  String toString() => 'Value($value)';
}

@bwhiteFC you can do it like this and it would be the same result:

  bool isValid() => value is Right;

But either way I publish a new version here 257a4c8 , that has isRight method.