initial commit
This commit is contained in:
45
example.java
Normal file
45
example.java
Normal file
@ -0,0 +1,45 @@
|
||||
import java.util.Optional;
|
||||
|
||||
class Example {
|
||||
public static void main(String[] args) {
|
||||
/* should print Hi */
|
||||
Optional<String> a = Optional.of("Hi");
|
||||
System.out.println(StOptional.reduce(a));
|
||||
|
||||
/* should print null */
|
||||
Optional<String> b = Optional.empty();
|
||||
System.out.println(StOptional.reduce(b));
|
||||
|
||||
/* should print null */
|
||||
Optional<String> 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> T reduce(Optional<T> 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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user