in.ashwanthkumar.utils.lang.option.Option Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of my-java-utils Show documentation
Show all versions of my-java-utils Show documentation
My personal set of utils that I take along with my java projects.
package in.ashwanthkumar.utils.lang.option;
/**
* Safely wrap around null values
* @param
*/
abstract public class Option {
protected T data;
public Option(T value) {
this.data = value;
}
public T getOrElse(T defaultValue) {
if (isEmpty()) return defaultValue;
else return data;
}
public boolean isDefined() {
return !isEmpty();
}
public boolean isEmpty() {
return data == null;
}
public abstract T get() throws IllegalStateException;
public static Option option(T value) {
if (value == null) return new None();
else return new Some(value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Option)) return false;
Option option = (Option) o;
if (data != null ? !data.equals(option.data) : option.data != null) return false;
return true;
}
@Override
public int hashCode() {
return data != null ? data.hashCode() : 0;
}
}