Last active
January 11, 2022 23:18
-
-
Save meowpunch/0c7acbdea914f1469c980d654c48a845 to your computer and use it in GitHub Desktop.
Improve geometry class with pattern matching, seal classes and records
This file contains 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
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