aQute.lib.exceptions.FunctionWithException Maven / Gradle / Ivy
package aQute.lib.exceptions;
import static java.util.Objects.requireNonNull;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Function interface that allows exceptions.
*
* @param the type of the argument
* @param the result type
*/
@FunctionalInterface
public interface FunctionWithException {
R apply(T t) throws Exception;
default Function orElseThrow() {
return t -> {
try {
return apply(t);
} catch (Exception e) {
throw Exceptions.duck(e);
}
};
}
default Function orElse(R orElse) {
return t -> {
try {
return apply(t);
} catch (Exception e) {
return orElse;
}
};
}
default Function orElseGet(Supplier extends R> orElseGet) {
requireNonNull(orElseGet);
return t -> {
try {
return apply(t);
} catch (Exception e) {
return orElseGet.get();
}
};
}
static Function asFunction(FunctionWithException unchecked) {
return unchecked.orElseThrow();
}
static Function asFunctionOrElse(FunctionWithException unchecked, R orElse) {
return unchecked.orElse(orElse);
}
static Function asFunctionOrElseGet(FunctionWithException unchecked,
Supplier extends R> orElseGet) {
return unchecked.orElseGet(orElseGet);
}
}