Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01B38FGKKam5SCGgwgduVAh3
1.5 KiB
5. Primitive types in patterns (JEP 532, fifth preview)
Prev: 4. Post-quantum TLS · Next: 6. Lazy constants
Compile and run with --enable-preview --release 27. Source: PrimitivePatterns, transcript 23.
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.
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).
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; source in Dominated.java.
Prev: 4. Post-quantum TLS · Next: 6. Lazy constants