Created
November 21, 2018 15:20
-
-
Save AungThiha/164023930249710e4163cd887e31a32d to your computer and use it in GitHub Desktop.
written based on Java 8 Optional to support Android API Level lower than 24
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Optional<M> { | |
| /** | |
| * Common instance for {@code empty()}. | |
| */ | |
| private static final Optional<?> EMPTY = new Optional<>(null); | |
| private final M value; | |
| public Optional(@Nullable M value) { | |
| this.value = value; | |
| } | |
| /** | |
| * Returns an {@code Optional} with the specified present non-null value. | |
| * | |
| * @param <T> the class of the value | |
| * @param value the value to be present, which must be non-null | |
| * @return an {@code Optional} with the value present | |
| * @throws NullPointerException if value is null | |
| */ | |
| public static <T> Optional<T> of(T value) { | |
| return new Optional<>(value); | |
| } | |
| /** | |
| * Returns an empty {@code Optional} instance. No value is present for this | |
| * Optional. | |
| * | |
| * @apiNote Though it may be tempting to do so, avoid testing if an object | |
| * is empty by comparing with {@code ==} against instances returned by | |
| * {@code Option.empty()}. There is no guarantee that it is a singleton. | |
| * Instead, use {@link #isPresent()}. | |
| * | |
| * @param <T> Type of the non-existent value | |
| * @return an empty {@code Optional} | |
| */ | |
| public static<T> Optional<T> empty() { | |
| @SuppressWarnings("unchecked") Optional<T> t = (Optional<T>) EMPTY; | |
| return t; | |
| } | |
| /** | |
| * Return {@code true} if there is a value present, otherwise {@code false}. | |
| * | |
| * @return {@code true} if there is a value present, otherwise {@code false} | |
| */ | |
| public boolean isPresent() { | |
| return this.value != null; | |
| } | |
| /** | |
| * Return {@code true} if the value is empty, the value may not be null but empty | |
| * | |
| * @return {@code true} if the value is empty, the value may not be null but empty | |
| */ | |
| public boolean isEmpty() { | |
| return this.value == null || | |
| (value instanceof Collection && ((Collection) value).isEmpty()) || | |
| (value instanceof Map && ((Map) value).isEmpty()) || | |
| (value instanceof Set && ((Set) value).isEmpty()); | |
| } | |
| public @NonNull M get() { | |
| if (value == null) { | |
| throw new NoSuchElementException("No value present"); | |
| } | |
| return value; | |
| } | |
| public @Nullable M getNullable() { | |
| return value; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment