Skip to content

Instantly share code, notes, and snippets.

@joshlong
Last active April 17, 2025 04:54
Show Gist options
  • Save joshlong/fcca98b7bbe0a09bd9927d138e970feb to your computer and use it in GitHub Desktop.
Save joshlong/fcca98b7bbe0a09bd9927d138e970feb to your computer and use it in GitHub Desktop.
a simple Java 23 program demonstrating some of the things showing how nice modern Java can be, based on the C# equivalent shown in https://youtu.be/1I3mWSiWNsI?feature=shared&t=374
// sdk install java 23.0.1-librca && sdk use java 23.0.1-librca
// java --enable-preview Main.java
record Point(int x, int y) {}
sealed interface Shape permits Rectangle, Circle {}
record Rectangle(int width, int height) implements Shape {}
record Circle(int radius) implements Shape {}
void main() {
var point = new Point(1, 2);
println(describePoint(point));
var shape = new Circle(5);
var area = calculateArea(shape);
println("Area of the shape: %s !%n".formatted( area));
}
String describePoint(Point point) {
return switch (point) {
case Point(int x, int y) when x == 0 && y == 0 -> "Origin";
case Point(int x, int y) when x == 1 && y == 2 -> "1,2";
default -> throw new IllegalStateException("Unexpected value: " + point);
};
}
double calculateArea(Shape shape) {
return switch (shape) {//exhaustive checking
case Rectangle(var height, var width) -> height * width;
case Circle(var radius) -> Math.PI * radius * radius;
};
}
@joshlong
Copy link
Author

Hi @paulk-asert that's amazing! thanks for sharing! i never thought i'd see the day Java holds a candle to Groovy or Kotlin. Nice. your example is exactly two lines shorter than the Java version, and that's because in Java you have to define

void main(){

and

}

i'm sure the groovy version could be made even more concise, and i appreciate that you were only doing a sort of similar-in-spirit comparison which kept it longer. still super nice.

here's the kotlin version for reference https://gist.github.com/joshlong/53fd8bddd0973a512454dc758eff550a

one thing i'm noticing is that java's version has this nice pattern match and destructure at the same time going on in the branch conditions. i kinda dig it.

@joshlong
Copy link
Author

here is for reference the original C# code against which i was comparing

Screenshot 2024-11-15 at 11 24 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment