Add Maybe.ifNothing(Runnable)
This commit is contained in:
parent
576b50fadb
commit
c5247d7c14
5 changed files with 45 additions and 0 deletions
|
@ -1,6 +1,11 @@
|
|||
CHANGELOG
|
||||
=========
|
||||
|
||||
0.9.0
|
||||
-----
|
||||
|
||||
* Add `Maybe.ifNothing(Runnable)`
|
||||
|
||||
0.8.0
|
||||
-----
|
||||
|
||||
|
|
|
@ -93,6 +93,11 @@ final class Just<T> implements Maybe<T> {
|
|||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifNothing(final Runnable runnable) {
|
||||
// ignore - not nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void orElseThrow(final Supplier<Exception> e) {
|
||||
// do not throw
|
||||
|
|
|
@ -142,4 +142,11 @@ public interface Maybe<T> extends Functor<T, Maybe<?>> {
|
|||
* @return this Maybe
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
|
|
@ -74,6 +74,11 @@ final class Nothing<T> implements Maybe<T> {
|
|||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ifNothing(final Runnable runnable) {
|
||||
runnable.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void orElseThrow(final Supplier<Exception> e) throws Exception {
|
||||
throw e.get();
|
||||
|
|
|
@ -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<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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue