Skip to content

Instantly share code, notes, and snippets.

@luochen1990
Created May 15, 2018 07:45
Show Gist options
  • Select an option

  • Save luochen1990/bf68301e1e4ceddaf7af1ea729c03073 to your computer and use it in GitHub Desktop.

Select an option

Save luochen1990/bf68301e1e4ceddaf7af1ea729c03073 to your computer and use it in GitHub Desktop.
ADT Sum Type in Java
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); }
}
@YSMull
Copy link
Copy Markdown

YSMull commented May 15, 2018

Adding some static methods help Either ease to use.

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

    public static <L,R> L fromLeft(L dft, Either<L,R> either) {
        return either.fromLeft(dft);
    }
    public static <L,R> R fromRight(R dft, Either<L,R> either) {
        return either.fromRight(dft);
    }
    public static <L,R> boolean isLeft(Either<L,R> either) {
        return either.isLeft();
    }
    public static <L,R> boolean isRight(Either<L,R> either) {
        return either.isRight();
    }
    public static <L,R,V> V either(Either<L,R> either, Function<L, V> fl, Function<R, V> fr) {
        return either.either(fl, fr);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment