Created
June 14, 2019 13:26
-
-
Save Pyrofab/91217b95c2049d3a1c99b6be3e8fa281 to your computer and use it in GitHub Desktop.
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
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