pattern matching

Testing a value against a shape, such as a type, a range or the values of its properties, and optionally extracting parts of it in the same step.

In more detail

Pattern matching replaces a type check followed by a cast with one construct, and the compiler tracks where the extracted parts are safe to use. In switch-like constructs, specific patterns must come before broad ones.

Examples

C#: kettle is { Price: > 20m and < 50m }
Java: if (value instanceof String text && !text.isBlank()) { ... }
Java 21: case Approved value -> "approved " + value.id();
if (value instanceof String text && !text.isBlank()) { ... }
case Approved value -> "approved " + value.id();

Related terms

Taught in

References

Certification courses