Last active
January 24, 2019 14:55
-
-
Save green-nick/33c038e535c5352521dc1c7c3f38a18c to your computer and use it in GitHub Desktop.
Null safety wrapper for objects. Base on Monad pattern
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
package ; | |
import javax.annotation.Nonnull; | |
import javax.annotation.Nullable; | |
public class Maybe<T> { | |
private static final Maybe EMPTY = new Maybe(); | |
private final T element; | |
private Maybe() { | |
this.element = null; | |
} | |
private Maybe(T element) { | |
this.element = element; | |
} | |
@Nonnull | |
public static <T> Maybe<T> of(@Nullable T element) { | |
return element == null ? EMPTY : new Maybe<>(element); | |
} | |
@Nonnull | |
public T getOrThrow() throws NullPointerException { | |
if (element == null) | |
throw new NullPointerException("Element is empty "); | |
else | |
return element; | |
} | |
@Nullable | |
public T getOrNull() { | |
return element; | |
} | |
@Nonnull | |
public T getElse(@Nonnull T another) { | |
return element == null ? another : element; | |
} | |
@Nonnull | |
public Maybe<T> apply(Action<T> func) { | |
if (element != null) func.call(element); | |
return this; | |
} | |
@Nonnull | |
public <U> Maybe<U> map(Function<T, U> func) { | |
return element == null ? EMPTY : Maybe.of(func.call(element)); | |
} | |
@Nonnull | |
public <U> Maybe<U> flatMap(Function<T, Maybe<U>> func) { | |
return element == null ? EMPTY : func.call(element); | |
} | |
@Nonnull | |
public Maybe<T> filter(Function<T, Boolean> filter) { | |
if (element == null) return this; | |
return filter.call(element) ? this : EMPTY; | |
} | |
public boolean isPresent() { | |
return element != null; | |
} | |
@Override | |
public String toString() { | |
return element == null ? "Maybe is empty" : "Maybe [" + | |
"element=" + element + | |
']'; | |
} | |
public interface Action<T> { | |
void call(T element); | |
} | |
public interface Function<T, U> { | |
U call(T element); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment