-
Notifications
You must be signed in to change notification settings - Fork 101
Closed
Labels
enhancementNew feature or requestNew feature or requestjavajava 21+recipeRecipe requestedRecipe requested
Description
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
Are you interested in contributing this feature to OpenRewrite?
Not at the moment
timtebeek, nicokosi and agostonbarna
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or requestjavajava 21+recipeRecipe requestedRecipe requested
Type
Projects
Status
Done