Created
October 25, 2017 22:03
-
-
Save msamujlo/5bc7f800710078da60146d1d27e116e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Optional; | |
import java.util.function.Supplier; | |
public class SuppliersExamples { | |
@Test | |
public void lazyValuation() throws Exception { | |
Optional<Integer> ok = executeDangerousAction(() -> 4 / 2); | |
Optional<Integer> divisionByZero = executeDangerousAction(() -> 4 / 0); | |
assertThat(ok).isPresent().hasValue(2); | |
assertThat(divisionByZero).isEmpty(); | |
} | |
private <A> Optional<A> executeDangerousAction(Supplier<A> action){ | |
A value = null; | |
try { | |
value = action.get(); | |
} catch (Exception e) { | |
} | |
return Optional.ofNullable(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment