Created
May 25, 2018 07:17
-
-
Save izhangzhihao/95d7fc96c942375cfe5372caf967c3d1 to your computer and use it in GitHub Desktop.
Optional of throwable
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.Function; | |
public class Option { | |
public static <T, V> Optional<V> ofThrowable(T it, Function<T, V> func) { | |
try { | |
return Optional.ofNullable(func.apply(it)); | |
} catch (Exception e) { | |
return Optional.empty(); | |
} | |
} | |
} |
nice!
Another option:
@FunctionalInterface
public interface ThrowableSupplier<T> {
T get() throws Exception;
}
public static <T> Optional<T> ofThrowable(final ThrowableSupplier<T> supplier) {
try {
return ofNullable(supplier.get());
} catch (final Exception ignored) {
return empty();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty useful! 👍