Skip to content

Instantly share code, notes, and snippets.

@kevinpet
Created February 8, 2015 21:51
Show Gist options
  • Save kevinpet/7375f3c8f4a4b49be3cc to your computer and use it in GitHub Desktop.
Save kevinpet/7375f3c8f4a4b49be3cc to your computer and use it in GitHub Desktop.
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"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment