Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Last active July 28, 2017 16:45
Show Gist options
  • Save SegFaultAX/a3871484b4c1e280a675a9727ac3b0f7 to your computer and use it in GitHub Desktop.
Save SegFaultAX/a3871484b4c1e280a675a9727ac3b0f7 to your computer and use it in GitHub Desktop.
Safely convert a function `T -> R throws E` to `T -> Optional<R>` [Java]
class Example {
<T, R, E extends Exception> Function<T, Optional<R>> safely(Function<T, R> fun, Class<E> exc) {
return v -> {
try {
return Optional.ofNullable(fun.apply(v));
} catch (Exception e) {
if (exc.isInstance(e)) {
return Optional.empty();
} else {
throw e;
}
}
};
}
public static void main(String[] args) {
Optional.ofNullable(possiblyNullString).flatMap(safely(Long::parseLong, NumberFormatException.class))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment