Skip to content

Instantly share code, notes, and snippets.

@wchargin
Created March 5, 2016 16:09
Show Gist options
  • Save wchargin/9a06ffc2b28d5f6468c2 to your computer and use it in GitHub Desktop.
Save wchargin/9a06ffc2b28d5f6468c2 to your computer and use it in GitHub Desktop.
an attempt at emulating algebraic data types in Java
import java.util.List;
class HistoryEvent {
private final HistoryEventItem item;
private static class HistoryEventItem {
}
private static final class WordPlayedItem extends HistoryEventItem {
private final int player;
private final List<String> wordsFormed;
public WordPlayedItem(int player, List<String> wordsFormed) {
this.player = player;
this.wordsFormed = wordsFormed;
}
}
private static final class ChallengedItem extends HistoryEventItem {
private final int player;
private final boolean successful;
public ChallengedItem(int player, boolean successful) {
this.player = player;
this.successful = successful;
}
}
private static final class PassedItem extends HistoryEventItem {
private final int player;
public PassedItem(int player) {
this.player = player;
}
}
private HistoryEvent(HistoryEventItem item) {
this.item = item;
}
public static HistoryEvent wordPlayed(int player, List<String> wordsFormed) {
return new HistoryEvent(new WordPlayedItem(player, wordsFormed));
}
public static HistoryEvent challenged(int player, boolean successful) {
return new HistoryEvent(new ChallengedItem(player, successful));
}
public static HistoryEvent passed(int player) {
return new HistoryEvent(new PassedItem(player));
}
public <R> R apply(HistoryEventConsumer<R> dispatcher) {
if (item instanceof WordPlayedItem) {
final WordPlayedItem data = (WordPlayedItem) item;
return dispatcher.onPlayWord(data.player, data.wordsFormed);
}
if (item instanceof ChallengedItem) {
final ChallengedItem data = (ChallengedItem) item;
return dispatcher.onChallenge(data.player, data.successful);
}
if (item instanceof PassedItem) {
final PassedItem data = (PassedItem) item;
return dispatcher.onPass(data.player);
}
throw new AssertionError(item.getClass());
}
}
interface HistoryEventConsumer<R> {
public R onPlayWord(int player, List<String> wordsFormed);
public R onChallenge(int player, boolean successful);
public R onPass(int player);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment