Add Maybe.ifNothing(Runnable)

This commit is contained in:
Paul Campbell 2018-07-07 18:21:35 +01:00
parent 576b50fadb
commit c5247d7c14
5 changed files with 45 additions and 0 deletions

View file

@ -1,6 +1,11 @@
CHANGELOG CHANGELOG
========= =========
0.9.0
-----
* Add `Maybe.ifNothing(Runnable)`
0.8.0 0.8.0
----- -----

View file

@ -93,6 +93,11 @@ final class Just<T> implements Maybe<T> {
return this; return this;
} }
@Override
public void ifNothing(final Runnable runnable) {
// ignore - not nothing
}
@Override @Override
public void orElseThrow(final Supplier<Exception> e) { public void orElseThrow(final Supplier<Exception> e) {
// do not throw // do not throw

View file

@ -142,4 +142,11 @@ public interface Maybe<T> extends Functor<T, Maybe<?>> {
* @return this Maybe * @return this Maybe
*/ */
Maybe<T> peek(Consumer<T> consumer); Maybe<T> peek(Consumer<T> 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);
} }

View file

@ -74,6 +74,11 @@ final class Nothing<T> implements Maybe<T> {
return this; return this;
} }
@Override
public void ifNothing(final Runnable runnable) {
runnable.run();
}
@Override @Override
public void orElseThrow(final Supplier<Exception> e) throws Exception { public void orElseThrow(final Supplier<Exception> e) throws Exception {
throw e.get(); throw e.get();

View file

@ -6,6 +6,7 @@ import org.junit.Test;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -171,4 +172,26 @@ public class MaybeTest implements WithAssertions {
assertThat(result.toOptional()).isEmpty(); assertThat(result.toOptional()).isEmpty();
} }
@Test
public void just_ifNothing_isIgnored() {
//given
final Maybe<Integer> 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<Integer> nothing = Maybe.nothing();
final AtomicBoolean capture = new AtomicBoolean(false);
//when
nothing.ifNothing(() -> capture.set(true));
//then
assertThat(capture).isTrue();
}
} }