Pattern matching has been a highly anticipated feature in Java, bringing more power and flexibility to the language. Java 21 introduces pattern matching for switch statements, which simplifies the code and reduces boilerplate. Let's explore how this new feature works and why it's beneficial.
Pattern matching for switch allows you to match a value against patterns, making the code more expressive and readable. Instead of using multiple if-else statements or complex switch cases, you can now write more concise and maintainable code.
Here's a simple example to illustrate how pattern matching for switch works:
static String formatterPatternSwitch(Object obj) { return switch (obj) { case Integer i -> String.format("int %d", i); case Long l -> String.format("long %d", l); case Double d -> String.format("double %f", d); case String s -> String.format("String %s", s); default -> obj.toString(); }; }
In this example, formatterPatternSwitch takes an Object and returns a formatted string based on its type. Here's a breakdown of what's happening:
Let's me give with detailed example case: Handling Different Shapes
Consider a scenario where you need to handle different shapes and calculate their areas. Here's how pattern matching for switch can simplify the code:
abstract sealed class Shape permits Circle, Square, Rectangle {} final class Circle extends Shape { double radius; Circle(double radius) { this.radius = radius; } } final class Square extends Shape { double side; Square(double side) { this.side = side; } } final class Rectangle extends Shape { double length, width; Rectangle(double length, double width) { this.length = length; this.width = width; } } static double calculateArea(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius * c.radius; case Square s -> s.side * s.side; case Rectangle r -> r.length * r.width; }; }
In this example:
Pattern matching for switch in Java 21 is a powerful feature that enhances code readability, conciseness, and type safety. By allowing you to match values against patterns directly in switch statements, it simplifies many common coding tasks. Java developers should definitely explore and adopt this feature to write cleaner and more maintainable code.
Feel free to modify or expand upon this section to suit your needs!
The above is the detailed content of Pattern Matching for Switch in Java 21. For more information, please follow other related articles on the PHP Chinese website!