Pattern Matching for Switch Example

1. Introduction

This blog post discusses Pattern Matching for switch, a new feature introduced in Java as a preview. This feature enhances the traditional switch statement, allowing for more expressive and flexible case labels.

Definition

Pattern Matching for switch extends the switch statement to work seamlessly with various types of data, not just primitives or enums. It can match types, destructure data, and eliminate the need for cumbersome if-else chains or type checking.

2. Program Steps

1. Define a class hierarchy to use with pattern matching.

2. Write a switch statement using pattern matching.

3. Test the switch statement with different types.

3. Code Program

// Class hierarchy
sealed interface Shape permits Circle, Rectangle {}

record Circle(double radius) implements Shape {}
record Rectangle(double length, double width) implements Shape {}

public class PatternMatchingSwitch {
    public static String getShapeDescription(Shape shape) {
        return switch (shape) {
            case Circle c -> "Circle with radius: " + c.radius();
            case Rectangle r -> "Rectangle with length: " + r.length() + " and width: " + r.width();
        };
    }

    public static void main(String[] args) {
        Shape circle = new Circle(5.0);
        Shape rectangle = new Rectangle(4.0, 3.0);

        System.out.println(getShapeDescription(circle));
        System.out.println(getShapeDescription(rectangle));
    }
}

Output:

Circle with radius: 5.0
Rectangle with length: 4.0 and width: 3.0

Explanation:

1. Shape is a sealed interface with two permitted implementations: Circle and Rectangle.

2. getShapeDescription method uses a switch statement with pattern matching. It checks the type of Shape and performs type-specific operations.

3. The switch statement uses pattern matching to identify the type of Shape and extracts its properties directly.

4. In main, getShapeDescription is called with instances of Circle and Rectangle, and the switch statement correctly identifies each shape and retrieves their specific properties.

5. This example demonstrates the clarity and expressiveness of Pattern Matching for switch, which makes the code more concise and readable.


Comments