Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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