From 7ebce8e14ff7afcf815a0211cbe2975157abf5df Mon Sep 17 00:00:00 2001 From: Benjamin Culkin Date: Mon, 8 Dec 2025 20:25:49 -0500 Subject: Add two function types for Closable functions ClosableFunction and ClosableThrowFunction are both function types that are used for binding a auto-closable resource to a function, representing a "thing that can only be done while a given resource is open" --- src/main/java/bjc/functypes/ClosableFunction.java | 34 +++++++++++++++++++++ .../java/bjc/functypes/ClosableThrowFunction.java | 35 ++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/main/java/bjc/functypes/ClosableFunction.java create mode 100644 src/main/java/bjc/functypes/ClosableThrowFunction.java (limited to 'src/main/java') 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 The input type + * @param The result type + */ +public interface ClosableFunction extends AutoCloseable, Function { + /** + * Create a ClosableFunction from a {@link AutoCloseable} and a {@link Function} + * + * @param The input type + * @param The result type + * @param f The function + * @param clos The AutoClosable + * @return The closable function + */ + public static ClosableFunction bindFunction(Function f, AutoCloseable clos) { + return new ClosableFunction() { + @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 The input type + * @param The result type + * @param The exception type + */ +public interface ClosableThrowFunction extends AutoCloseable, ThrowFunction { + /** + * Create a ClosableFunction from a {@link AutoCloseable} and a {@link Function} + * + * @param The input type + * @param The result type + * @param f The function + * @param clos The AutoClosable + * @return The closable function + */ + public static ClosableThrowFunction bindFunction(ThrowFunction f, AutoCloseable clos) { + return new ClosableThrowFunction() { + @Override + public R apply(T t) throws E { + return f.apply(t); + } + + @Override + public void close() throws Exception { + clos.close(); + } + }; + } +} -- cgit v1.2.3