diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-05-07 12:51:23 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-05-07 12:51:23 -0400 |
| commit | 87ae1dfc8d8cb7b51d7bda4750ce841bbe691cfc (patch) | |
| tree | 290f31282898bd39300c70646c6fe2b65832886a /BJC-Utils2/src/main/java/bjc/utils/data/Option.java | |
| parent | fb7d03388e298258563c22abda1bd46cdaf991b7 (diff) | |
General changes
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc/utils/data/Option.java')
| -rw-r--r-- | BJC-Utils2/src/main/java/bjc/utils/data/Option.java | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java new file mode 100644 index 0000000..9f6d448 --- /dev/null +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java @@ -0,0 +1,74 @@ +package bjc.utils.data; + +import java.util.function.Function; +import java.util.function.UnaryOperator; + +/** + * A holder that may or may not contain a value + * + * @author ben + * + * @param <ContainedType> + * The type of the value that may or may not be held + */ +public class Option<ContainedType> implements IHolder<ContainedType> { + private ContainedType held; + + /** + * Create a new optional, using the given initial value + * + * @param seedValue + * The initial value for the optional + */ + public Option(ContainedType seedValue) { + held = seedValue; + } + + @Override + public <BoundType> IHolder<BoundType> bind( + Function<ContainedType, IHolder<BoundType>> binder) { + if (held == null) { + return new Option<>(null); + } + + return binder.apply(held); + } + + @Override + public <MappedType> IHolder<MappedType> map( + Function<ContainedType, MappedType> mapper) { + if (held == null) { + return new Option<>(null); + } + + return new Option<>(mapper.apply(held)); + } + + @Override + public IHolder<ContainedType> transform( + UnaryOperator<ContainedType> transformer) { + if (held != null) { + held = transformer.apply(held); + } + + return this; + } + + @Override + public <UnwrappedType> UnwrappedType unwrap( + Function<ContainedType, UnwrappedType> unwrapper) { + if (held == null) { + return null; + } + + return unwrapper.apply(held); + } + + @Override + public <NewType> Function<ContainedType, IHolder<NewType>> lift( + Function<ContainedType, NewType> func) { + return (val) -> { + return new Option<>(func.apply(val)); + }; + } +} |
