Skip to content

Instantly share code, notes, and snippets.

@maxbechtold
Last active January 8, 2021 08:19
Show Gist options
  • Save maxbechtold/5b8cbdd6593fd1e269ec2211fe6d914f to your computer and use it in GitHub Desktop.
Save maxbechtold/5b8cbdd6593fd1e269ec2211fe6d914f to your computer and use it in GitHub Desktop.
package maxbe.common;
import java.util.function.Function;
/**
* Taken and extended from http://codingjunkie.net/functional-iterface-exceptions/
*
* @author Max Bechtold
*/
@FunctionalInterface
public interface UnsafeFunction<T, R> extends Function<T, R> {
@Override
default R apply(T t) {
try {
return applyThrows(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
R applyThrows(T t) throws Exception;
/**
* Allows to use method references for signatures with throws-clauses in method chains of the Stream API. This works by wrapping checked exceptions in
* RuntimeExceptions and hiding the necessary cast to UnsafeFunction with this identity method.
*/
static <X, Y> UnsafeFunction<X, Y> unsafe(UnsafeFunction<X, Y> function) {
return function;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment