Skip to content

Instantly share code, notes, and snippets.

@benhardy
Created August 5, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhardy/112642313026040d274117c02b059132 to your computer and use it in GitHub Desktop.
Save benhardy/112642313026040d274117c02b059132 to your computer and use it in GitHub Desktop.
/**
* I know Either is a well known class in Scala, but I'm wondering if I've stumbled onto a well known pattern with this
* extract() function?
*/
public static final class Either<A,B> {
private final A left;
private final B right;
public boolean ifLeft(@Nonnull Consumer<A> todo){
if (left != null) {
todo.accept(left);
return true;
}
return false;
}
public boolean ifRight(@Nonnull Consumer<B> todo) {
if (right != null) {
todo.accept(right);
return true;
}
return false;
}
public <C> C extract(@Nonnull Function<A,C> extractLeft, @Nonnull Function<B,C> extractRight) {
if (left != null) {
return extractLeft.apply(left);
}
return extractRight.apply(right);
}
static <X> Either<X, ?> left(@Nonnull X a) {
return new Either<>(a, null);
}
static <Y> Either<?, Y> right(@Nonnull Y b) {
return new Either<>(null, b);
}
/** use static factories left() and right() */
private Either(A a, B b) {
this.left = a;
this.right = b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment