JEP 488: Primitive Types in Patterns, instanceof, and switch (Second Preview)
🧠 What is JEP 488?
It extends pattern matching (
instanceof,switch) to support primitive types likeint,long,double, etc.
Before JEP 488, instanceof and switch patterns were limited to reference types. Now, you can write cleaner, type-safe, and less error-prone code for primitives too.
🤔 Problem Before JEP 488
You couldn’t match record fields with different primitive types in patterns — even if conversion was safe.
record JsonNumber(double d) implements JsonValue {}
Object json = new JsonNumber(30); // OK: int → double
if (json instanceof JsonNumber(int a)) {
// ❌ ERROR before JEP 488
}Why? Because:
Pattern matching required exact type match (here:
double, notint)The compiler refused to do automatic narrowing conversions (double → int)
Run :
PrimitiveSwitchDemoIts simple demo of literal matching on primitive value
Run :
PrimitiveNestedPatternsIt shows how to use primitives in embedded Pattern Matching. Print at the end shows how primitive types are converted.
Last updated