From d9c0cd4cacb2b9e57db8d5359a837869bb651ed4 Mon Sep 17 00:00:00 2001 From: Squibid Date: Thu, 9 May 2024 22:39:43 -0400 Subject: initial commit --- StOptional.java | 36 ++++++++++++++++++++++++++++++++++++ example.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 StOptional.java create mode 100644 example.java diff --git a/StOptional.java b/StOptional.java new file mode 100644 index 0000000..308d29c --- /dev/null +++ b/StOptional.java @@ -0,0 +1,36 @@ +/* + * copyright (c) squibid 2024 under the Beerware license. + * + * If we meet some day, and you think this stuff is worth it, you can buy me a + * beer in return. + */ + +import java.util.Optional; + +/** + * Stop Optionals from being used! + * safely reducing optionals back to their original types. + */ +public final class StOptional { + /** + * Reduce any optional down to it's original type + * + * @param o Optional to reduce to it's original type + * @return value of optional in original type or null + */ + public static final T reduce(Optional o) { + return nullish(o) ? null : o.get(); + } + + /** + * Checks if Optional is null or empty + * + * @param o Optional optional to check for null like properties + * @return boolean true if null or empty, false otherwise + */ + public static final boolean nullish(Optional o) { + if (o == null || o.isEmpty()) + return true; + return false; + } +} diff --git a/example.java b/example.java new file mode 100644 index 0000000..f3d8858 --- /dev/null +++ b/example.java @@ -0,0 +1,45 @@ +import java.util.Optional; + +class Example { + public static void main(String[] args) { + /* should print Hi */ + Optional a = Optional.of("Hi"); + System.out.println(StOptional.reduce(a)); + + /* should print null */ + Optional b = Optional.empty(); + System.out.println(StOptional.reduce(b)); + + /* should print null */ + Optional c = null; + System.out.println(StOptional.reduce(c)); + } +} + +/** + * Stop Optionals from being used! + * safely reducing optionals back to their original types. + */ +final class StOptional { + /** + * Reduce any optional down to it's original type + * + * @param o Optional to reduce + * @return value of optional + */ + public static final T reduce(Optional o) { + return nullish(o) ? null : o.get(); + } + + /** + * Checks if Optional is null or empty + * + * @param o Optional + * @return boolean true if null or empty, false otherwise + */ + public static final boolean nullish(Optional o) { + if (o == null || o.isEmpty()) + return true; + return false; + } +} -- cgit v1.2.1