diff --git a/CHANGELOG.md b/CHANGELOG.md index f11af30..dcc7c0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## [0.3.0] - Add equality and hash override + +Either now overrides equality and hash. +> Thanks to @memishood for creating the [issue](https://github.com/avdosev/either_dart/issues/5) + ## [0.2.0] - Update Future[Either] Updated to support `FutureOr` instead of `Future`: diff --git a/lib/src/either.dart b/lib/src/either.dart index 48e2904..1efbe67 100644 --- a/lib/src/either.dart +++ b/lib/src/either.dart @@ -82,6 +82,17 @@ abstract class Either { static Either condLazy( bool test, Lazy leftValue, Lazy rightValue) => test ? Right(rightValue()) : Left(leftValue()); + + @override + bool operator ==(Object obj) { + return this.fold( + (left) => obj is Left && left == obj.value, + (right) => obj is Right && right == obj.value, + ); + } + + @override + int get hashCode => fold((left) => left.hashCode, (right) => right.hashCode); } /// Used for "failure" diff --git a/pubspec.yaml b/pubspec.yaml index d3cc9db..afb2873 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: either_dart description: Error handler library for type-safe and easy work with errors on Dart and Flutter. Either is an alternative to Nullable value and Exceptions. -version: 0.2.0 +version: 0.3.0 homepage: https://github.com/avdosev repository: https://github.com/avdosev/either_dart diff --git a/test/either_test.dart b/test/either_test.dart index 56bbc63..56428cd 100644 --- a/test/either_test.dart +++ b/test/either_test.dart @@ -102,4 +102,47 @@ void main() { .isRight, true); }); + + group('equal', () { + test('Left and Left', () { + final x = Left('test'); + final z = Left('test'); + expect(x, z); + expect(x.hashCode, z.hashCode); + expect(x == z, true); + expect(x != z, false); + expect(Left('1111'), isNot(equals(Left('2222')))); + expect(Left('1111'), equals(Left('1111'))); + expect(Left(null), Left(null)); + expect(Left(null).hashCode, Left(null).hashCode); + }); + + test('Right and Left', () { + final x = Right('test'); + final z = Left('test'); + expect(x != z, true); + expect(x == z, false); + + expect(Left('1111'), isNot(equals(Right('2222')))); + expect(Left('1111'), isNot(equals(Right('1111')))); + expect(Right('1111'), isNot(equals(Left('2222')))); + expect(Right('1111'), isNot(equals(Left('1111')))); + expect(Left(null), isNot(equals(Right(null)))); + expect(Right(null), isNot(equals(Left(null)))); + }); + + test('Right and Right', () { + final x = Right('test'); + final z = Right('test'); + + expect(x, z); + expect(x.hashCode, z.hashCode); + expect(x == z, true); + expect(x != z, false); + expect(Right('1111'), isNot(equals(Right('2222')))); + expect(Right('1111'), equals(Right('1111'))); + expect(Right(null), Right(null)); + expect(Right(null).hashCode, Right(null).hashCode); + }); + }); }