Created
May 15, 2018 07:45
-
-
Save luochen1990/bf68301e1e4ceddaf7af1ea729c03073 to your computer and use it in GitHub Desktop.
ADT Sum Type in Java
This file contains hidden or 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.function.Function; | |
| public class EitherExample { | |
| public static void main(String[] args) { | |
| Either<String, Integer> x = new Left<>("hello"); | |
| Either<String, Integer> y = new Right<>(123); | |
| System.out.println("hello"); | |
| System.out.println(x); | |
| System.out.println(y); | |
| } | |
| } | |
| abstract class Either<L, R> { | |
| public abstract boolean isLeft(); | |
| public abstract boolean isRight(); | |
| public abstract L fromLeft(L dft); | |
| public abstract R fromRight(R dft); | |
| public abstract <V> V either(Function<L, V> fl, Function<R, V> fr); //pattern matching | |
| } | |
| class Left<L, R> extends Either<L, R> { | |
| private L value; | |
| public Left(L x){ value = x; } | |
| public boolean isLeft() { return true; } | |
| public boolean isRight() { return false; } | |
| public L fromLeft(L dft) { return value; } | |
| public R fromRight(R dft) { return dft; } | |
| public <V> V either(Function<L, V> fl, Function<R, V> fr) { return fl.apply(value); } | |
| } | |
| class Right<L, R> extends Either<L, R> { | |
| private R value; | |
| public Right(R x){ value = x; } | |
| public boolean isLeft() { return false; } | |
| public boolean isRight() { return true; } | |
| public L fromLeft(L dft) { return dft; } | |
| public R fromRight(R dft) { return value; } | |
| public <V> V either(Function<L, V> fl, Function<R, V> fr) { return fr.apply(value); } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Adding some static methods help
Eitherease to use.