Created
July 24, 2023 14:47
-
-
Save cboudereau/5d44f0bdaac4cd2cefdda41e51dbf64d to your computer and use it in GitHub Desktop.
Abstract Data Type / Sum type / Discriminated union for java
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 characters
// from https://github.com/cboudereau/adt-java17-presentation > https://github.com/fteychene/adt-java17-presentation | |
package com.example; | |
public class App { | |
public enum Direction { | |
NORTH, | |
SOUTH, | |
EAST, | |
WEST | |
} | |
public record Chain(Command a, Command b) implements Command { | |
} | |
public record Cute() implements Command { | |
} | |
public record Move(Integer steps) implements Command { | |
} | |
public record TakeOver() implements Command { | |
} | |
public record Turn(Direction direction) implements Command { | |
} | |
public sealed interface Command permits Chain, Cute, Move, TakeOver, Turn { | |
default Command then(Command next) { | |
return new Chain(this, next); | |
} | |
} | |
public static void handle(Command command) { | |
switch (command) { | |
case Move m -> display("Move of " + m.steps()); | |
case Turn t -> { | |
switch (t.direction()) { | |
case NORTH -> display("Turning north"); | |
case SOUTH -> display("Turning south"); | |
case WEST -> display("Turning east"); | |
case EAST -> display("Turning west"); | |
} | |
} | |
case Cute cute -> display("Do something cute no one can resist"); | |
case TakeOver takeOver -> display("Start taking over the WORLD !!!!!!!"); | |
case Chain chain -> { | |
handle(chain.a()); | |
handle(chain.b()); | |
} | |
} | |
} | |
public static void display(String message) { | |
System.out.println("\uD83E\uDD16 : " + message); | |
} | |
public static void main(String[] args) { | |
var command = new Chain(new Cute(), new Move(2)); | |
handle(command); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment