Add Maybe.match(Consumer,Runnable)

This commit is contained in:
Paul Campbell 2018-07-12 18:45:02 +01:00
parent c64284872c
commit d66c4c8502
4 changed files with 46 additions and 2 deletions

View file

@ -98,6 +98,11 @@ final class Just<T> implements Maybe<T> {
// ignore - not nothing
}
@Override
public void match(final Consumer<T> justMatcher, final Runnable nothingMatcher) {
justMatcher.accept(value);
}
@Override
public void orElseThrow(final Supplier<Exception> e) {
// do not throw

View file

@ -149,4 +149,12 @@ public interface Maybe<T> extends Functor<T, Maybe<?>> {
* @param runnable the runnable to call if this is a Nothing
*/
void ifNothing(Runnable runnable);
/**
* Matches the Maybe, either just or nothing, and performs either the Consumer, for Just, or Runnable for nothing.
*
* @param justMatcher the Consumer to pass the value of a Just to
* @param nothingMatcher the Runnable to call if the Maybe is a Nothing
*/
void match(Consumer<T> justMatcher, Runnable nothingMatcher);
}

View file

@ -34,6 +34,7 @@ import java.util.stream.Stream;
* @param <T> the type of the missing content
* @author Paul Campbell (pcampbell@kemitix.net)
*/
@SuppressWarnings("methodcount")
final class Nothing<T> implements Maybe<T> {
static final Maybe<?> INSTANCE = new Nothing<>();
@ -79,6 +80,11 @@ final class Nothing<T> implements Maybe<T> {
runnable.run();
}
@Override
public void match(final Consumer<T> justMatcher, final Runnable nothingMatcher) {
nothingMatcher.run();
}
@Override
public void orElseThrow(final Supplier<Exception> e) throws Exception {
throw e.get();

View file

@ -194,4 +194,29 @@ public class MaybeTest implements WithAssertions {
assertThat(capture).isTrue();
}
@Test
public void just_whenMatch_thenJustTriggers() {
//given
final Maybe<Integer> maybe = Maybe.just(1);
//then
maybe.match(
just -> assertThat(just).isEqualTo(1),
() -> fail("Not nothing")
);
}
@Test
public void nothing_whenMatch_thenNothingTriggers() {
//given
final Maybe<Integer> maybe = Maybe.nothing();
final AtomicBoolean flag = new AtomicBoolean(false);
//when
maybe.match(
just -> fail("Not a just"),
() -> flag.set(true)
);
//then
assertThat(flag).isTrue();
}
}