diff --git a/CHANGELOG b/CHANGELOG index e1f6ff8..c4444f2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,11 @@ CHANGELOG ========= +0.9.0 +----- + +* Add `Maybe.ifNothing(Runnable)` + 0.8.0 ----- diff --git a/src/main/java/net/kemitix/mon/maybe/Just.java b/src/main/java/net/kemitix/mon/maybe/Just.java index 77a258f..85aea43 100644 --- a/src/main/java/net/kemitix/mon/maybe/Just.java +++ b/src/main/java/net/kemitix/mon/maybe/Just.java @@ -93,6 +93,11 @@ final class Just implements Maybe { return this; } + @Override + public void ifNothing(final Runnable runnable) { + // ignore - not nothing + } + @Override public void orElseThrow(final Supplier e) { // do not throw diff --git a/src/main/java/net/kemitix/mon/maybe/Maybe.java b/src/main/java/net/kemitix/mon/maybe/Maybe.java index 02b1ffc..be04b67 100644 --- a/src/main/java/net/kemitix/mon/maybe/Maybe.java +++ b/src/main/java/net/kemitix/mon/maybe/Maybe.java @@ -142,4 +142,11 @@ public interface Maybe extends Functor> { * @return this Maybe */ Maybe peek(Consumer consumer); + + /** + * Run the runnable if the Maybe is a Nothing, otherwise do nothing. + * + * @param runnable the runnable to call if this is a Nothing + */ + void ifNothing(Runnable runnable); } diff --git a/src/main/java/net/kemitix/mon/maybe/Nothing.java b/src/main/java/net/kemitix/mon/maybe/Nothing.java index 05f033d..d1c7193 100644 --- a/src/main/java/net/kemitix/mon/maybe/Nothing.java +++ b/src/main/java/net/kemitix/mon/maybe/Nothing.java @@ -74,6 +74,11 @@ final class Nothing implements Maybe { return this; } + @Override + public void ifNothing(final Runnable runnable) { + runnable.run(); + } + @Override public void orElseThrow(final Supplier e) throws Exception { throw e.get(); diff --git a/src/test/java/net/kemitix/mon/MaybeTest.java b/src/test/java/net/kemitix/mon/MaybeTest.java index 575826a..2b82337 100644 --- a/src/test/java/net/kemitix/mon/MaybeTest.java +++ b/src/test/java/net/kemitix/mon/MaybeTest.java @@ -6,6 +6,7 @@ import org.junit.Test; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.stream.Stream; @@ -171,4 +172,26 @@ public class MaybeTest implements WithAssertions { assertThat(result.toOptional()).isEmpty(); } + @Test + public void just_ifNothing_isIgnored() { + //given + final Maybe just = Maybe.just(1); + final AtomicBoolean capture = new AtomicBoolean(false); + //when + just.ifNothing(() -> capture.set(true)); + //then + assertThat(capture).isFalse(); + } + + @Test + public void nothing_ifNothing_isCalled() { + //given + final Maybe nothing = Maybe.nothing(); + final AtomicBoolean capture = new AtomicBoolean(false); + //when + nothing.ifNothing(() -> capture.set(true)); + //then + assertThat(capture).isTrue(); + } + }