Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz
Created April 12, 2012 07:26
Show Gist options
  • Save gakuzzzz/2365427 to your computer and use it in GitHub Desktop.
Save gakuzzzz/2365427 to your computer and use it in GitHub Desktop.
sumtype on java way
public abstract class Base {
public static class A extends Base { ... }
public static class B extends Base { ... }
public static Base createA(...) { return new A(...); }
public static Base createB(...) { return new B(...); }
public static interface Visitor<T> {
T visit(A a);
T visit(B b);
}
public abstract <T> T accept(Visitor<T> visitor);
}
Base base = Base.createA(...);
Integer n = base.accept(new Base.Visitor<Integer> {
public Integer visit(Base.A a) { return 1; }
public Integer visit(Base.B b) { return 2; }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment