Skip to content

Instantly share code, notes, and snippets.

@Pyrofab
Created June 14, 2019 13:26
Show Gist options
  • Save Pyrofab/91217b95c2049d3a1c99b6be3e8fa281 to your computer and use it in GitHub Desktop.
Save Pyrofab/91217b95c2049d3a1c99b6be3e8fa281 to your computer and use it in GitHub Desktop.
import java.util.function.Function;
import java.util.Optional;
interface ObjectPath<T, R> extends Function<T, R> {
default R get(T t) {
R r = this.apply(t);
if (r == null) {
throw new NoSuchElementException();
}
return r;
}
default Optional<R> optionally(T t) {
return Optional.ofNullable(this.apply(t));
}
@Override
default <V> ObjectPath<T, V> andThen(Function<? super R, ? extends V> after) {
return (s) -> {
R r = this.apply(s);
return r != null ? after.apply(r) : null;
}
}
default <V> ObjectPath<T, V> specialize(Class<V> specialization) {
return (s) -> {
R r = this.apply(s);
return specialization.isInstance(r) ? (V) r : null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment