diff options
| -rw-r--r-- | src/main/java/bjc/functypes/ClosableFunction.java | 34 | ||||
| -rw-r--r-- | src/main/java/bjc/functypes/ClosableThrowFunction.java | 35 |
2 files changed, 69 insertions, 0 deletions
diff --git a/src/main/java/bjc/functypes/ClosableFunction.java b/src/main/java/bjc/functypes/ClosableFunction.java new file mode 100644 index 0000000..a559bfc --- /dev/null +++ b/src/main/java/bjc/functypes/ClosableFunction.java @@ -0,0 +1,34 @@ +package bjc.functypes; + +import java.util.function.Function; + +/** + * A function associated with a closable resource + * + * @param <T> The input type + * @param <R> The result type + */ +public interface ClosableFunction<T, R> extends AutoCloseable, Function<T, R> { + /** + * Create a ClosableFunction from a {@link AutoCloseable} and a {@link Function} + * + * @param <T> The input type + * @param <R> The result type + * @param f The function + * @param clos The AutoClosable + * @return The closable function + */ + public static <T, R> ClosableFunction<T, R> bindFunction(Function<T, R> f, AutoCloseable clos) { + return new ClosableFunction<T, R>() { + @Override + public R apply(T t) { + return f.apply(t); + } + + @Override + public void close() throws Exception { + clos.close(); + } + }; + } +} diff --git a/src/main/java/bjc/functypes/ClosableThrowFunction.java b/src/main/java/bjc/functypes/ClosableThrowFunction.java new file mode 100644 index 0000000..856f15d --- /dev/null +++ b/src/main/java/bjc/functypes/ClosableThrowFunction.java @@ -0,0 +1,35 @@ +package bjc.functypes; + +import java.util.function.Function; + +/** + * A (possibly throwing) function associated with a closable resource + * + * @param <T> The input type + * @param <R> The result type + * @param <E> The exception type + */ +public interface ClosableThrowFunction<T, R, E extends Throwable> extends AutoCloseable, ThrowFunction<T, R, E> { + /** + * Create a ClosableFunction from a {@link AutoCloseable} and a {@link Function} + * + * @param <T> The input type + * @param <R> The result type + * @param f The function + * @param clos The AutoClosable + * @return The closable function + */ + public static <T, R, E extends Throwable> ClosableThrowFunction<T, R, E> bindFunction(ThrowFunction<T, R, E> f, AutoCloseable clos) { + return new ClosableThrowFunction<T, R, E>() { + @Override + public R apply(T t) throws E { + return f.apply(t); + } + + @Override + public void close() throws Exception { + clos.close(); + } + }; + } +} |
