All Downloads are FREE. Search and download functionalities are using the official Maven repository.

aQute.lib.exceptions.FunctionWithException Maven / Gradle / Ivy

There is a newer version: 7.0.0
Show newest version
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 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 orElseGet) {
		return unchecked.orElseGet(orElseGet);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy