Last active
October 1, 2017 14:42
-
-
Save ryugoo/8de36d41c249165b0b3344ba8ccbcf59 to your computer and use it in GitHub Desktop.
Either class using Lightweight Stream API
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
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