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 like int, 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, not int)

  • The compiler refused to do automatic narrowing conversions (double → int)

Run :

PrimitiveSwitchDemo

Its simple demo of literal matching on primitive value

Run :

PrimitiveNestedPatterns

It shows how to use primitives in embedded Pattern Matching. Print at the end shows how primitive types are converted.

Last updated