Skip to content

Instantly share code, notes, and snippets.

@tomsontom
Last active October 19, 2022 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomsontom/24b75e24c7ed1917c94f615e0cc1007e to your computer and use it in GitHub Desktop.
Save tomsontom/24b75e24c7ed1917c94f615e0cc1007e to your computer and use it in GitHub Desktop.
Java-19 Switch / Source Compat Problem
package blo;
public class MySwitch {
public interface NamedItem {
public String name();
}
public static class MyTypeA /* implements NamedItem*/ {
private final String value;
public MyTypeA(String value) {
this.value = value;
}
public String name() {
return this.value;
}
}
public static class MyTypeB implements NamedItem {
private final String value;
public MyTypeB(String value) {
this.value = value;
}
public String name() {
return this.value;
}
}
static class ExtractSwitch {
static String extractName(Object o) {
return switch( o ) {
case NamedItem item -> item.name();
case MyTypeA t -> t.name();
default -> o.toString();
};
}
}
static class ExtractMethod {
static String extractName(NamedItem item) {
return item.name();
}
static String extractName(MyTypeA item) {
return item.name();
}
static String extractName(Object o) {
return o.toString();
}
}
static class ExtractIf {
static String extractName(Object o) {
if( o instanceof NamedItem item ) {
return item.name();
} else if( o instanceof MyTypeA t ) {
return t.name();
} else {
return o.toString();
}
}
}
public static void main(String[] args) {
System.err.println(ExtractSwitch.extractName(new MyTypeA("MyType")));
System.err.println(ExtractSwitch.extractName(new MyTypeB("MyTypeX")));
System.err.println(ExtractSwitch.extractName(new Object()));
System.err.println("----");
System.err.println(ExtractMethod.extractName(new MyTypeA("MyType")));
System.err.println(ExtractMethod.extractName(new MyTypeB("MyTypeX")));
System.err.println(ExtractMethod.extractName(new Object()));
System.err.println("----");
System.err.println(ExtractIf.extractName(new MyTypeA("MyType")));
System.err.println(ExtractIf.extractName(new MyTypeB("MyTypeX")));
System.err.println(ExtractIf.extractName(new Object()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment