Skip to content

Instantly share code, notes, and snippets.

@meowpunch
Last active January 11, 2022 23:18
Show Gist options
  • Save meowpunch/0c7acbdea914f1469c980d654c48a845 to your computer and use it in GitHub Desktop.
Save meowpunch/0c7acbdea914f1469c980d654c48a845 to your computer and use it in GitHub Desktop.
Improve geometry class with pattern matching, seal classes and records
sealed interface Shape {}
record Point(double x, double y) {}
record Square (Point topLeft, double side) implements Shape {}
record Rectangle (Point topLeft, double height, double width) implements Shape {}
record Circle (Point center, double radius) implements Shape {}
class Geometry {
public final double PI = 3.141592653589793;
public double area(Shape shape) {
return switch(shape) {
case Square s -> s.side() * s.side();
case Rectangle r -> r.height() * r.width();
case Circle c -> PI * c.radius() * c.radius();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment