Created
September 23, 2020 10:10
-
-
Save kalgon/39e5763c00b2347b611b8bc3265af1b6 to your computer and use it in GitHub Desktop.
Either
This file contains 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.Objects; | |
import java.util.Optional; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public final class Either<Left, Right> { | |
public static <L, R> Either<L, R> ofLeft(L left) { | |
return new Either<>(Objects.requireNonNull(left), null); | |
} | |
public static <L, R> Either<L, R> ofRight(R right) { | |
return new Either<>(null, Objects.requireNonNull(right)); | |
} | |
private final Left left; | |
private final Right right; | |
private Either(Left left, Right right) { | |
this.left = left; | |
this.right = right; | |
} | |
public void accept(Consumer<? super Left> left, Consumer<? super Right> right) { | |
if (isLeft()) { | |
left.accept(this.left); | |
} else { | |
right.accept(this.right); | |
} | |
} | |
public <Result> Result reduce(Function<? super Left, Result> left, Function<? super Right, Result> right) { | |
return isLeft() ? left.apply(this.left) : right.apply(this.right); | |
} | |
public <X, Y> Either<X, Y> map(Function<? super Left, X> left, Function<? super Right, Y> right) { | |
return isLeft() ? ofLeft(left.apply(this.left)) : ofRight(right.apply(this.right)); | |
} | |
public Optional<Left> getLeft() { | |
return isLeft() ? Optional.of(left) : Optional.empty(); | |
} | |
public Optional<Right> getRight() { | |
return isRight() ? Optional.of(right) : Optional.empty(); | |
} | |
public boolean isLeft() { | |
return left != null; | |
} | |
public boolean isRight() { | |
return right != null; | |
} | |
@Override | |
public String toString() { | |
return isLeft() ? String.format("Left[%s]", left) : String.format("Right[%s]", right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment