rewrite-migrate-java icon indicating copy to clipboard operation
rewrite-migrate-java copied to clipboard

Pattern Matching for switch in Java 21 / JEP 411

Open matsev opened this issue 2 years ago • 2 comments

What problem are you trying to solve?

Add recipe for JEP 441: Pattern Matching for switch to improve Java 21 migration (and possibly also for the related JEP 440: Record Patterns).

Describe the solution you'd like

The two examples copied from the JEP 441: Pattern Matching for switch project (there are more):

instanceof

// Prior to Java 21
static String formatter(Object obj) {
    String formatted = "unknown";
    if (obj instanceof Integer i) {
        formatted = String.format("int %d", i);
    } else if (obj instanceof Long l) {
        formatted = String.format("long %d", l);
    } else if (obj instanceof Double d) {
        formatted = String.format("double %f", d);
    } else if (obj instanceof String s) {
        formatted = String.format("String %s", s);
    }
    return formatted;
}
// As of Java 21
static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}

Switches and null

// Prior to Java 21
static void testFooBarOld(String s) {
    if (s == null) {
        System.out.println("Oops!");
        return;
    }
    switch (s) {
        case "Foo", "Bar" -> System.out.println("Great");
        default           -> System.out.println("Ok");
    }
}
// As of Java 21
static void testFooBarNew(String s) {
    switch (s) {
        case null         -> System.out.println("Oops");
        case "Foo", "Bar" -> System.out.println("Great");
        default           -> System.out.println("Ok");
    }
}

Have you considered any alternatives or workarounds?

no

Additional context

  • #305

Are you interested in contributing this feature to OpenRewrite?

Not at the moment

matsev avatar Sep 26 '23 11:09 matsev

Pattern matching for switch is now fully supported

  • https://github.com/openrewrite/rewrite/pull/4661

Record pattern matching is print idempotent for now, I'll continue working on that next week!

Laurens-W avatar Jan 17 '25 13:01 Laurens-W

A little too eager closing issues here; while we support parsing pattern matching in switch, we should also support migrating to that style. We should now be able to convert the above into runnable unit tests on a draft PR to get that migration work going as well.

timtebeek avatar Jan 17 '25 15:01 timtebeek