Created
April 12, 2012 07:26
-
-
Save gakuzzzz/2365427 to your computer and use it in GitHub Desktop.
sumtype on java way
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
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); | |
} |
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
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