Skip to content

Instantly share code, notes, and snippets.

@benweidig
Created May 16, 2020 17:07
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 benweidig/d7f7d326768ad67fdcf8a6c78d69b1b9 to your computer and use it in GitHub Desktop.
Save benweidig/d7f7d326768ad67fdcf8a6c78d69b1b9 to your computer and use it in GitHub Desktop.
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
public class Either<L, R> {
public static <L, R> Either<L, R> left(L value) {
return new Either<>(value, null);
}
public static <L, R> Either<L, R> right(R value) {
return new Either<>(null, value);
}
private final Optional<L> left;
private final Optional<R> right;
private Either(L left, R right) {
this.left = Optional.ofNullable(left);
this.right = Optional.ofNullable(right);
}
private Either(Optional<L> left, Optional<R> right) {
this.left = left;
this.right = right;
}
public <T> T map(Function<? super L, ? extends T> mapLeft, //
Function<? super R, ? extends T> mapRight) {
return this.left.<T> map(mapLeft) //
.orElseGet(() -> this.right.map(mapRight).get());
}
public <T> Either<T, R> mapLeft(Function<? super L, ? extends T> leftFn) {
return new Either<>(this.left.map(leftFn), //
this.right);
}
public <T> Either<L, T> mapRight(Function<? super R, ? extends T> rightFn) {
return new Either<>(this.left, //
this.right.map(rightFn));
}
public void apply(Consumer<? super L> leftFn, Consumer<? super R> rightFn) {
this.left.ifPresent(leftFn);
this.right.ifPresent(rightFn);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment