Skip to content

Instantly share code, notes, and snippets.

@msamujlo
Created October 25, 2017 22:03
Show Gist options
  • Save msamujlo/5bc7f800710078da60146d1d27e116e6 to your computer and use it in GitHub Desktop.
Save msamujlo/5bc7f800710078da60146d1d27e116e6 to your computer and use it in GitHub Desktop.
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