Skip to content

Instantly share code, notes, and snippets.

@kevinpet
Created February 8, 2015 20:39
Show Gist options
  • Save kevinpet/5f01ed4b93888653302a to your computer and use it in GitHub Desktop.
Save kevinpet/5f01ed4b93888653302a to your computer and use it in GitHub Desktop.
Java destructuring visitor example
abstract class Foo {
abstract <T> T match(Visitor<T> visitor);
interface Visitor<T> {
T caseManyBar();
T caseBar(int i);
T caseBaz(String s);
}
static class Bar extends Foo {
private int bar;
private Bar(int bar) {
this.bar = bar;
}
@Override
<T> T match(Visitor<T> visitor) {
return bar > 10 ? visitor.caseManyBar() : visitor.caseBar(bar);
}
}
static class Baz extends Foo {
private String baz;
private Baz(String baz) {
this.baz = baz;
}
@Override
<T> T match(Visitor<T> visitor) {
return visitor.caseBaz(baz);
}
}
static void handle(Foo f) {
System.out.println(f.match(new Visitor<String>() {
@Override
public String caseBar(int i) {
return "I have " + i + " bars";
}
@Override
public String caseManyBar() {
return "I have many bars";
}
@Override
public String caseBaz(String s) {
return "I have the " + s + " baz";
}
}));
}
public static void main(String[] args) {
handle(new Bar(42));
handle(new Bar(3));
handle(new Baz("Luhrmann"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment