How to access items inside a sealed interface and records in Java

1 Answer

0 votes
public class Main {

    // 1. Define metadata using an immutable record
    public record Metadata(String name, boolean isActive) {}

    // 2. Define a sealed interface representing the variant dimensions (the union equivalent)
    public sealed interface Dimension permits Dimension.Circle, Dimension.Rectangle {
        
        record Circle(float radius) implements Dimension {}
        record Rectangle(float width, float height) implements Dimension {}
    }

    // 3. Define the main container record holding ID, metadata, and the variant dimension
    public record Shape(int id, Metadata metadata, Dimension dimension) {}

    /**
     * Safely accesses and prints items from nested records and sealed variants
     * using modern Java pattern matching switch.
     */
    public static void printShapeProperties(Shape shape) {
        if (shape == null) {
            System.out.println("Error: Received null shape.");
            return;
        }

        // Accessing nested record fields using automatic getter methods
        System.out.println("Shape ID: " + shape.id());
        System.out.println("Shape Name: " + shape.metadata().name());
        System.out.println("Status: " + (shape.metadata().isActive() ? "Active" : "Inactive"));

        // Pattern matching switch handles the variant types safely and exhaustively
        switch (shape.dimension()) {
            case Dimension.Circle c -> {
                System.out.println("Type: Circle");
                System.out.println("Radius: " + c.radius());
            }
            case Dimension.Rectangle r -> {
                System.out.println("Type: Rectangle");
                System.out.println("Width: " + r.width() + ", Height: " + r.height());
            }
        }
        System.out.println("------------------------------------");
    }

    public static void main(String[] args) {
        // Initialize a Circle shape
        Shape myCircle = new Shape(
            101,
            new Metadata("Unit Circle", true),
            new Dimension.Circle(5.5f)
        );

        // Initialize a Rectangle shape
        Shape myRectangle = new Shape(
            102,
            new Metadata("Bounding Box", false),
            new Dimension.Rectangle(10.0f, 20.0f)
        );

        // Print properties
        printShapeProperties(myCircle);
        printShapeProperties(myRectangle);
    }
}


/*
run:

Shape ID: 101
Shape Name: Unit Circle
Status: Active
Type: Circle
Radius: 5.5
------------------------------------
Shape ID: 102
Shape Name: Bounding Box
Status: Inactive
Type: Rectangle
Width: 10.0, Height: 20.0
------------------------------------

*/

 



answered 9 hours ago by avibootz
...