diff --git a/README.md b/README.md index 337b0b2..45c4ec4 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,8 @@ class Test { ### Result +A Monad. + A container for method return values that may raise an Exception. Useful for when a checked exceptions can't be added to the method signature. diff --git a/src/main/java/net/kemitix/mon/result/Success.java b/src/main/java/net/kemitix/mon/result/Success.java index 830b41e..9093b08 100644 --- a/src/main/java/net/kemitix/mon/result/Success.java +++ b/src/main/java/net/kemitix/mon/result/Success.java @@ -24,6 +24,7 @@ package net.kemitix.mon.result; import lombok.RequiredArgsConstructor; import net.kemitix.mon.maybe.Maybe; +import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -76,6 +77,16 @@ class Success implements Result { return value; } + @Override + public boolean equals(Object other) { + return other instanceof Success && Objects.equals(value, ((Success) other).value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + @Override public String toString() { return String.format("Result.Success{value=%s}", value); diff --git a/src/test/java/net/kemitix/mon/ResultMonadTest.java b/src/test/java/net/kemitix/mon/ResultMonadTest.java new file mode 100644 index 0000000..8a8470f --- /dev/null +++ b/src/test/java/net/kemitix/mon/ResultMonadTest.java @@ -0,0 +1,39 @@ +package net.kemitix.mon; + +import net.kemitix.mon.result.Result; +import org.assertj.core.api.WithAssertions; +import org.junit.Test; + +import java.util.function.Function; + +public class ResultMonadTest implements WithAssertions { + + @Test + public void leftIdentity() { + //given + final int value = 1; + final Result result = Result.ok(value); + final Function> f = i -> Result.ok(i * 2); + //then + assertThat(result.flatMap(f)).isEqualTo(f.apply(value)); + } + + @Test + public void rightIdentity() { + //given + final Result result = Result.ok(1); + //then + assertThat(result.flatMap(Result::ok)).isEqualTo(result); + } + + @Test + public void associativity() { + //given + final Result result = Result.ok(1); + final Function> f = i -> Result.ok(i * 2); + final Function> g = i -> Result.ok(i + 6); + //then + assertThat(result.flatMap(f).flatMap(g)).isEqualTo(result.flatMap(x -> f.apply(x).flatMap(g))); + } + +}