com.danielsomerfield.util.Maybe.groovy Maven / Gradle / Ivy
package com.danielsomerfield.util
abstract class Maybe {
private static final Maybe NOTHING = new Nothing();
public abstract boolean exists()
public abstract T getValue()
public abstract Maybe map(Closure mapper)
public static Maybe some(T value) {
return value == null ? NOTHING : new Some(value)
}
public static Maybe nothing() {
NOTHING
}
private static class Some extends Maybe {
private T value;
public Some(final T value) {
this.value = value
}
public boolean exists() {
true
}
public T getValue(){
value
}
@Override
def Maybe map(final Closure mapper) {
some(mapper(value))
}
boolean equals(final o) {
if (this.is(o)) return true
if (!(o instanceof Some)) return false
final Some some = (Some) o
if (value != some.value) return false
return true
}
int hashCode() {
return value.hashCode()
}
@Override
public String toString() {
"Some{" +
"value=" + value +
'}';
}
}
private static class Nothing extends Maybe {
@Override
boolean exists() {
return false // TODO
}
@Override
Object getValue() {
throw new IllegalStateException("Cannot get value of Nothing")
}
@Override
Maybe map(final Closure mapper) {
this
}
public String toString(){"Nothing"}
}
}