-
-
Save joshlong/fcca98b7bbe0a09bd9927d138e970feb to your computer and use it in GitHub Desktop.
// 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; | |
}; | |
} |
yah. but this doesn't show measuring the area of a point, does it?
Awesome. Have always love every version of Java
Well, his point (ha) was that calculateArea(somePoint) could return zero instead of throwing.
I think I prefer the model that point is not 2-dimensional and the concept of area only exists for 2-dimensional shapes.
If we are flexing some fresh Java, it needs a sealed interface Shape {}
for the chef's kiss!
kotlin ?
This just looks like a less interesting version? that println looks weird since it's a function, and the cases in describePoint are more verbose. I think Java made it better than what Groovy offers in this situation.
Groovy lets you drop the brackets for function calls in places where there is no ambiguity. The Groovy case statement is more powerful but we'll probably offer destructuring as well at some point. But the main value add here, apart from the script syntax, is if you want to run on JDK8-21, the Groovy version gives you that.
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.
Isn't the area of a Point 0?