fr.lirmm.boreal.util.stream.ThrowingFunction Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of integraal-util Show documentation
Show all versions of integraal-util Show documentation
Util objects for integraal
The newest version!
package fr.lirmm.boreal.util.stream;
import java.util.function.Function;
/**
* This functional interface allows to not catch an Exception in a
* lambda expression : use it at your own risk, the exception
* becomes unchecked.
* It is recommended to use it only in a method that can throw the
* Exception type that is unchecked. So the exception can be
* checked when using the method.
*
* Source : http://4comprehension.com/sneakily-throwing-exceptions-in-lambda-expressions-in-java/
*
* @author Guillaume Pérution-Kihli
* @param type of the input element
* @param type of the result element
*/
@FunctionalInterface
public interface ThrowingFunction {
/**
* Redefine the apply method to be able to declare that an exception is thrown
* @param t the element
* @return the result of the function
* @throws Exception if an exception is thrown by the inner method
*/
R apply(T t) throws Exception;
/**
* @param type of the exception to throw
* @param type of the result element
* @param t the exception
* @return nothing
* @throws T the initial exception
*/
@SuppressWarnings("unchecked")
static R sneakyThrow(Exception t) throws T {
throw (T) t;
}
/**
* @param type of the input element
* @param type of the result element
* @param f the function to call
* @return the result of the function
*/
static Function unchecked(ThrowingFunction f) {
return t -> {
try {
return f.apply(t);
} catch (Exception ex) {
return ThrowingFunction.sneakyThrow(ex);
}
};
}
}