Pattern Matching Switch Sealed
Use pattern matching with switch on sealed types for exhaustive handling.
Code
public sealed interface Shape permits Circle, Square, Rectangle {}
public record Circle(double radius) implements Shape {}
public record Square(double side) implements Shape {}
public record Rectangle(double w, double h) implements Shape {}
public class Area {
public static double compute(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square sq -> sq.side() * sq.side();
case Rectangle r -> r.w() * r.h();
};
}
}Inside the snippet
The working surface is the classes Shape, Circle, Square and Rectangle and the function compute — everything else is wiring.
Putting it to use
The entry-point signature is public static double compute(Shape s)
Core lines
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square sq -> sq.side() * sq.side();
case Rectangle r -> r.w() * r.h();
};
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `compute` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.