Last active
January 8, 2021 08:19
-
-
Save maxbechtold/5b8cbdd6593fd1e269ec2211fe6d914f to your computer and use it in GitHub Desktop.
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
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