Created
February 8, 2015 21:51
-
-
Save kevinpet/7375f3c8f4a4b49be3cc to your computer and use it in GitHub Desktop.
Revisions
-
kevinpet created this gist
Feb 8, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,52 @@ abstract class Foo { abstract <T> T match(Visitor<T> visitor); interface Visitor<T> { T caseBar(Bar b); T caseBaz(Baz b); } static class Bar extends Foo { final int bar; private Bar(int bar) { this.bar = bar; } @Override <T> T match(Visitor<T> visitor) { return visitor.caseBar(this); } } static class Baz extends Foo { final String baz; private Baz(String baz) { this.baz = baz; } @Override <T> T match(Visitor<T> visitor) { return visitor.caseBaz(this); } } static void handle(Foo f) { System.out.println(f.match(new Visitor<String>() { @Override public String caseBar(Bar b) { return "I have " + b.bar + " bars"; } @Override public String caseBaz(Baz b) { return "I have the " + b.baz + " baz"; } })); } public static void main(String[] args) { handle(new Bar(42)); handle(new Baz("Luhrmann")); } }