Last active
July 28, 2017 16:45
-
-
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]
This file contains hidden or 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
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