Last active
April 17, 2025 04:54
-
-
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
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
// 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; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.