Files
javademos/docs/05-primitive-patterns.md

33 lines
1.5 KiB
Markdown

# 5. Primitive types in patterns (JEP 532, fifth preview)
Prev: [4. Post-quantum TLS](04-post-quantum-tls.md) · Next: [6. Lazy constants](06-lazy-constants.md)
Compile and run with `--enable-preview --release 27`. Source: [`PrimitivePatterns`](../jep-tour/src/PrimitivePatterns.java), transcript [23](output/23-primitive-patterns.txt).
## The idea in one sentence
A pattern may now name a primitive type, and the test is **"can this value be converted to that type without losing information?"**. It is an exactness test, not a cast.
```java
int small = 100, big = 300;
small instanceof byte // true : 100 fits
big instanceof byte // false : a byte holds -128..127
16_777_216 instanceof float // true
16_777_217 instanceof float // false : a float has a 24-bit significand
```
You can also `switch` on a `long`, `float`, `double` or `boolean`, use `case int` against an `Integer`, and put a narrowing primitive in a record pattern:
`Reading(byte c)` matches `Reading[celsius=36]` but not `Reading[celsius=4000]` ([23](output/23-primitive-patterns.txt)).
## The compile error you will meet
Dominance rules apply. Put `case Integer i` before `case int primitive` and the second label can never match:
```
error: this case label is dominated by a preceding case label
```
The real text is in [20-broken-dominated.txt](output/20-broken-dominated.txt); source in [`Dominated.java`](../jep-tour/src/broken/Dominated.java).
Prev: [4. Post-quantum TLS](04-post-quantum-tls.md) · Next: [6. Lazy constants](06-lazy-constants.md)