Last active
October 19, 2022 21:41
-
-
Save tomsontom/24b75e24c7ed1917c94f615e0cc1007e to your computer and use it in GitHub Desktop.
Java-19 Switch / Source Compat Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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