Skip to content

Instantly share code, notes, and snippets.

@ryugoo
Last active October 1, 2017 14:42
Show Gist options
  • Save ryugoo/8de36d41c249165b0b3344ba8ccbcf59 to your computer and use it in GitHub Desktop.
Save ryugoo/8de36d41c249165b0b3344ba8ccbcf59 to your computer and use it in GitHub Desktop.
Either class using Lightweight Stream API
public final class Either<Left, Right> {
private final Optional<Left> left;
private final Optional<Right> right;
private Either(Optional<Left> left, Optional<Right> right) {
this.left = left;
this.right = right;
}
public static <Left, Right> Either<Left, Right> left(@NonNull Left value) {
return new Either<>(Optional.of(value), Optional.empty());
}
public static <Left, Right> Either<Left, Right> right(@NonNull Right value) {
return new Either<>(Optional.empty(), Optional.of(value));
}
public <T> Either<T, Right> mapLeft(Function<? super Left, ? extends T> func) {
return new Either<>(this.left.map(func), this.right);
}
public <T> Either<Left, T> mapRight(Function<? super Right, ? extends T> func) {
return new Either<>(this.left, this.right.map(func));
}
public void apply(Consumer<? super Left> lConsumer, Consumer<? super Right> rConsumer) {
this.left.ifPresent(lConsumer);
this.right.ifPresent(rConsumer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment